How to perform POST request involving JSONObject in java-jersey? - java

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

Related

Google Http delete with body (Json)

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 "{}").

I am getting 400 Bad Request for ReST call only in internet explorer

In our running application, one of GET request starts giving response as 400 Bad Request in Internet Explorer.
On investigating , I found that GET request doesn't have queryParameters what were expected by ReST call.
As it is giving response in another browsers like Chrome, Mozilla,
how can I proceed further ?
this is Request currently being triggered--
Method of request is GET
https://XXXXXXXXX/XXX/XXXXXXXXX/XXXXXXXXX/XXXXXXXXX/XXXXXXXXX?{%22numRecords%22:1000,%22start%22:0}&_=1487576597960
and queryParameters in #QueryParam expected by ReST api are-
-numRecords
-start
I know by the above GET request, numRecords and start will not get captured by api backend.
So , is there any chance, if my GET request lack of any #QueryParam will lead to 400 Bad request response.
I found that GET request doesn't have queryParameters
You can use query parameters in GET requests as you've provided in your example like this: http://host?queryParam1=value1. however it's not possible to pass a request body as you can do for POST or PUT requests to provide JSON encoded data for example. You can work around this by adding the JSON AND URL encoded payload to a query parameter. But you endpoint explicitely has to be able to read this parameter. So you should add this parameter to your definiotn like in this example for JAX-RS:
#GET
#Path("my-endpoint")
public String request(
#PathParam("payload") JsonObject payload
) {
What you've tried is to simply pass the payload data without specifing the name of the request parameter.
Hope this helps.

Create a HTTP GET request which sends JSON data in body with Scala?

I am having a problem when i integrate API of our partner. They always use Json data in body of HTTP request for both "POST" and "GET" method.
I'm using scalaj library for creating HTTP request but it can not send json data in Body for GET request. when i put json data to body, the Method will change to POST automatically.
I also tried to use default HttpUrlConnection in Java, but it have same problem. When i call setDoOutput method, HttpUrlConnection will change Method to POST.
How can I solve this problem in Scala?

How to send "parameters" to all HTTP request methods?

I'm trying to write a Java client (with Apache HttpClient) for the Gengo API which makes use of HTTP GET, POST, PUT and DELETE. However for every RESTful API "method" that they expose, you must pass your API key and signature as "parameters".
Would this mean query string parameters, POST variables, key-value pair headers, or something else?
I guess I'm just confused by what is meant by the word "parameters" in the context of all these different HTTP request methods. In other words, how would I pass the API key as a "parameter" to their API when I could be using GET, POST, PUT or DELETE? My understanding was that only HTTP GET can handle query string params, and that HTTP POST can only handle POST variables. And I have never used PUT or DELETE before so I'm not sure what they require.
So I ask: what mechanism can I use to send the API key/signature via all 4 types of request methods, or do they all support the processing of query string parameters? Thanks in advance.
You can try this. It works for my HttpClient application with POST request.
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(name, value);
......
For Example, I set the connection timeout:
httpClient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, httpTimeout);
Then later, to send(execute) the request:
HttpResponse response = httpClient.execute([My HttpPost instance was here, but I think you can use HttpGet, HttpPut, and HttpDelete here as well]);
All verbs can use request parameters (also known as query parameters) and they will be available to the server in the same way regardless of if you also send a body.
In your example (Gengo) there is a good example on there page about authentication.

How can I POST using Java and include parameters and a raw request body?

I am communicating with a web service that expects a POST parameter and also expect Request body. I have confirmed that such a POST request can be done using a REST Console I have, but I am unable to make such a request in Java using Apache libraries.
In the code below, I am able to POST to the web service, and it correctly receives the contents of the variable raw_body. If I uncomment the first of the two commented lines, the web service receives the "fname" parameter, but it no longer receives the body of the POST.
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
...
HttpClient httpClient = new HttpClient();
String urlStr = "http://localhost:8080/MyRestWebService/save";
PostMethod method = new PostMethod(urlStr);
String raw_body = "This is a very long string, much too long to be just another parameter";
RequestEntity re = new StringRequestEntity(raw_body, "text/xml", "UTF-16");
//method.addParameter("fname", "test.txt");
//httpClient.getParams().setParameter("fname", "test.txt");
method.setRequestEntity(re);
How can I transmit both the parameter and the body?
You could use the setQueryString method to add the parameters to the URL that is being POSTed to. From a RESTful perspective I'd argue you should normally not be doing that, however, since a POST should represent a call to a resource and anything that would qualify for a query parameter should be included in the representation that is being transferred in the request body...or it should represent qualification of the resource itself in which case it should be part of the path that is posted to which could then be extracted by the controller using #PathVariable/#PathParam or something similar. So in your case you could also be looking for something like POST /MyRestWebService/files/test.txt or more fittingly a PUT if you're saving the resource and know the URI. The code on the server could pull the filename out from a URL pattern.
You need to make a POST request using multipart-form. Here is the example:
Apache HttpClient making multipart form post
Alternatively, you can make a POST request with the content (parameters and files) encoded using application/x-www-form-urlencoded but it is not recommended when you want to make a POST request with large content, like files.

Categories

Resources