I would like to send this JSON message below, with the HTTP DELETE method.
For this project is necessary to use OAuth2. So I use the dependency google-oauth. Foreach HTTP request I use the dependency google client.
{
"propertie" : true/false,
"members" : [
"String value is shown here"
]
}
In my project I used this code below, but I cannot send the JSON message with the HTTP DELETE method.
Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
JsonArray members = new JsonArray();
JsonPrimitive element = new JsonPrimitive("String value is shown here");
members.add(element);
JsonObject closeGroupchat = new JsonObject();
closeGroupchat.addProperty("propertie", false);
closeGroupchat.add("members", members);
Gson gson = new Gson();
HttpContent hc = new ByteArrayContent("application/json", gson.toJson(closeGroupchat).getBytes());
HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
HttpRequest httpreq = requestFactory.buildRequest(HttpMethods.DELETE, genericUrl, hc);
return httpreq.execute();
Next error occurs:
java.lang.IllegalArgumentException: DELETE with non-zero content length is not supported
Can someone help me with this problem?
Your problem is that your HTTP DELETE request contains a body, which it shouldn't. When you delete a resource, you need to supply the URL to delete. Any body in the HTTP request would be meaningless, because the intention is to instruct the server to delete a resource at a particular URL. The same thing can often happen for GET requests - a body is meaningless because you're trying to retrieve a body.
For details on HTTP DELETE request bodies, see this SO question on the subject. Note that while request bodies may technically be permitted by the HTTP spec, based on your error message, your client library doesn't allow it.
To fix the problem, try passing a null value for hc, or a value that just wraps an empty JSON string (by which I mean using "", not "{}").
Related
I have been struggling to simply perform a GET request to the Spotify API and parse the results of the request. I haven't been able to successfully do it despite trying to follow the docs. I am trying to achieve this within an Actor. I have tried making the HttpEntity a strict HttpEntity but this returns an error. I am not sure if this is due to dependency issues or if it is simply the incorrect approach. What I would like to do is obtain the entire payload of the response and parse it to then return it to another actor. I am unsure what should go inside of the try block to achieve this. Thanks very much.
ActorSystem actorSystem = getContext().getSystem();
Http http = Http.get(actorSystem);
String endpoint = "https://api.spotify.com/v1/artists/1moxjboGR7GNWYIMWsRjgG/top-tracks?market=IE";
Authorization authorization = Authorization.oauth2("REDACTED");
HttpRequest request = HttpRequest.create().withUri(endpoint).addHeader(authorization);
CompletionStage<HttpResponse> responseFuture = http.singleRequest(request)
responseFuture.thenAccept(response -> {
try {
}
Have tried casting entity to a strict entity but this results in an error.
I have the following code to create a JSON object:
Client client = ClientBuilder.newClient();
//response is the value of some GET request I performed before
JSONObject root=new JSONObject(response.readEntity(String.class));
//url is assigned to URL to which I wanted to POST.
WebTarget target2=client.target(url);
Response response2=target.request(MediaType.APPLICATION_JSON_TYPE);
response2.post(*what goes here*);
What do I need to put inside that last post?
"Inside the post function what exactly should be written."
Look at the SyncInvoker API. Look at the different post methods. You will choose one of these, depending on what type of response you want.
The Entity argument can simply be written as Entity.json(yourRequestObject), which automatically configures the request as Content-Type:application/json
In my java client application, I am accessing a endpoint URL and could able to get response back, but it is in HTML code!.
Method : Post
resource.accept(MediaType.APPLICATION_JSON_TYPE);
WebResource resource = Client.create().resource(
communicatorVO.getTargetURL());
String **response** = resource.queryParams(communicatorVO.getFormData()).type(MediaType.APPLICATION_JSON_TYPE).post(String.class, gson.toJson(communicatorVO.getRequestObject()));
The response object always contains HTML code! How to get the actual data?
If I try using chrome restful client, am getting below response.
{
"access_token" : "YOUR_NEW_ACCESS_TOKEN",
"token_type" : "bearer",
"expires_in" : 10800,
"refresh_token" : "YOUR_REFRESH_TOKEN",
"scope" : "write read offline_access"
}
This issue has been resolved.
I added type & accept in single line and it started returning expected json response. Now I can parse the json into any java object.
Code :
response = resource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept(MediaType.APPLICATION_JSON_TYPE).post(ClientResponse.class, communicatorVO.getFormData());;
i'm trying to use google-http-java-client on android and parse JSON responses from my server.
do do that i'm using the following code (provided by the examples of the project)
private static final HttpTransport HTTP_TRANSPORT = AndroidHttp.newCompatibleTransport();
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
HttpRequestFactory requestFactory = HTTP_TRANSPORT
.createRequestFactory(new HttpRequestInitializer() {
#Override
public void initialize(HttpRequest request) {
request.setParser(new JsonObjectParser(JSON_FACTORY));
}
});
HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(url + paramsList));
HttpResponse response = request.execute();
and everything works fine for new objects with
result = response.parseAs(PxUser.class);
but i need to update an existing object with the data from the json string.
with jackson only i can use the following code but with the google client i cannot find any solution.
InputStream in = -get-http-reponse-
ObjectMapper mapper = new ObjectMapper();
ObjectReader reader = mapper.readerForUpdating(MySingleton.getInstance());
reader.readValue(InputStream in);
so i need a way to update an existing object just like with this jackson example but by using the client.
is there a way? do i have to use jackson-databind.jar? how can i accomplish this?
thanks in advance
PS: i can switch to gson if its needed, no problem
It depends on whatever endpoint is receiving the API call, and what it expects the request to look like.
The Google HTTP Java Client simply handles the processes like making the call, encoding and decoding an object, exponential backoff, etc for you. It's up to you to create the request that does what you want and how the server expects it to look.
Likely, the API you're making the request to expects an object update to be made with a PUT request. The updated object is likely going to be the content of the request, encoded in some specific format. Let's assume JSON, since you're parsing JSON responses. So for the purpose of example, let's say you're going to request an object, modify it, then send it back.
First, you get the resource and parse it into your object:
PxUser myUser = response.parseAs(PxUser.class);
Then you modify the object somehow
myUser.setName("Frodo Baggins");
Now you want to send it back to the server as a JSON object in a PUT request:
// httpbin.org is a wonderful URL to test API calls against as it returns whatever if received.
GenericUrl url = new GenericUrl("http://httpbin.org/put");
JsonHttpContent content = new JsonHttpContent(new JacksonFactory(), myUser);
HttpRequest request = requestFactory.buildPutRequest(url, content);
HttpResponse response = request.execute();
System.out.println(response.parseAsString());
The specifics of how you encode and update your content is totally up to you and the API's specification. This is especially easy if you're creating the server receiving the call too.
If you're working with a preexisting API, you may want to update the question with the
specific problem (API "x" requires a response that looks like Blah; how do I do that in the google-http-java-client).
If you're working with a Google API, you'll want to be using the google-api-java-client which does all of this work for you.
I am trying to make a Http POST request using apache HTTP client. I am trying to copy contents of an HTTP POST request (received at my application) to another HTTP POST request (initiated from my application to another URL). Code is shown below:
httpPost = new HttpPost(inputURL);
// copy headers
for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements();) {
String headerName = e.nextElement().toString();
httpPost.setHeader(headerName, request.getHeader(headerName));
}
BufferedInputStream clientToProxyBuf = new BufferedInputStream(request.getInputStream());
BasicHttpEntity basicHttpEntity = new BasicHttpEntity();
basicHttpEntity.setContent(clientToProxyBuf);
basicHttpEntity.setContentLength(clientToProxyBuf.available());
httpPost.setEntity(basicHttpEntity);
HttpResponse responseFromWeb = httpclient.execute(httpPost);
Basically, I am trying to implement a proxy application which will get a url as parameter, froward the request to the URL and then serve pages etc in custom look and feel.
Here request is HttpServletRequest. I am facing problem in setting content length. Through debugging I found out that clientToProxyBuf.available() is not giving me correct length of input stream and I am getting Http error 400 IE and Error 354 (net::ERR_CONTENT_LENGTH_MISMATCH): The server unexpectedly closed the connection in chrome.
Am I doing it wrong? Is there any other way to achieve it?
The available() function doesn't provide the actual length of the content of the stream, rather
Returns the number of bytes that can be read from this input stream without blocking. (From javadoc)
I would suggest you to first read the whole content from the stream, and then set that to the content, rather than passing the stream object. That way, you will also have the actual length of the content.
It was rather simple and very obvious. I just needed to get content length from header as:
basicHttpEntity.setContentLength(Integer.parseInt(request.getHeader("Content-Length")));