How to use options with HttpPost

I am using a RESTfull webservice with this method:

@POST @Consumes({"application/json"}) @Path("create/") public void create(String str1, String str2){ System.out.println("value 1 = " + str1); System.out.println("value 2 = " + str2); } 

In my Android application, I want to call this method. How to provide the correct values ​​to parameters using org.apache.http.client.methods.HttpPost;

I noticed that I can use the @HeaderParam annotation and just add headers to the HttpPost object. Is it correct? Do it like:

 httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("str1", "a value"); httpPost.setHeader("str2", "another value"); 

Using the setEntity method on httpPost will not work. It sets only the str1 parameter using json string. When using it as:

 JSONObject json = new JSONObject(); json.put("str1", "a value"); json.put("str2", "another value"); HttpEntity e = new StringEntity(json.toString()); httpPost.setEntity(e); //server output: value 1 = {"str1":"a value","str2":"another value"} 
+45
java json android web-services
Nov 14 '11 at 10:28
source share
3 answers

To set parameters in HttpPostRequest , you can use BasicNameValuePair , something like this:

  HttpClient httpclient; HttpPost httppost; ArrayList<NameValuePair> postParameters; httpclient = new DefaultHttpClient(); httppost = new HttpPost("your login link"); postParameters = new ArrayList<NameValuePair>(); postParameters.add(new BasicNameValuePair("param1", "param1_value")); postParameters.add(new BasicNameValuePair("param2", "param2_value")); httpPost.setEntity(new UrlEncodedFormEntity(postParameters, "UTF-8")); HttpResponse response = httpclient.execute(httpPost); 
+87
Nov 14 '11 at
source

You can also use this approach if you want to pass some http parameters and send a json request:

(note: I added to some additional code only that it helps any other future readers)

 public void postJsonWithHttpParams() throws URISyntaxException, UnsupportedEncodingException, IOException { //add the http parameters you wish to pass List<NameValuePair> postParameters = new ArrayList<>(); postParameters.add(new BasicNameValuePair("param1", "param1_value")); postParameters.add(new BasicNameValuePair("param2", "param2_value")); //Build the server URI together with the parameters you wish to pass URIBuilder uriBuilder = new URIBuilder("http://google.ug"); uriBuilder.addParameters(postParameters); HttpPost postRequest = new HttpPost(uriBuilder.build()); postRequest.setHeader("Content-Type", "application/json"); //this is your JSON string you are sending as a request String yourJsonString = "{\"str1\":\"a value\",\"str2\":\"another value\"} "; //pass the json string request in the entity HttpEntity entity = new ByteArrayEntity(yourJsonString.getBytes("UTF-8")); postRequest.setEntity(entity); //create a socketfactory in order to use an http connection manager PlainConnectionSocketFactory plainSocketFactory = PlainConnectionSocketFactory.getSocketFactory(); Registry<ConnectionSocketFactory> connSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", plainSocketFactory) .build(); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(connSocketFactoryRegistry); connManager.setMaxTotal(20); connManager.setDefaultMaxPerRoute(20); RequestConfig defaultRequestConfig = RequestConfig.custom() .setSocketTimeout(HttpClientPool.connTimeout) .setConnectTimeout(HttpClientPool.connTimeout) .setConnectionRequestTimeout(HttpClientPool.readTimeout) .build(); // Build the http client. CloseableHttpClient httpclient = HttpClients.custom() .setConnectionManager(connManager) .setDefaultRequestConfig(defaultRequestConfig) .build(); CloseableHttpResponse response = httpclient.execute(postRequest); //Read the response String responseString = ""; int statusCode = response.getStatusLine().getStatusCode(); String message = response.getStatusLine().getReasonPhrase(); HttpEntity responseHttpEntity = response.getEntity(); InputStream content = responseHttpEntity.getContent(); BufferedReader buffer = new BufferedReader(new InputStreamReader(content)); String line; while ((line = buffer.readLine()) != null) { responseString += line; } //release all resources held by the responseHttpEntity EntityUtils.consume(responseHttpEntity); //close the stream response.close(); // Close the connection manager. connManager.close(); } 
+2
Jun 15 '16 at 9:53 on
source

Generally speaking, HTTP POST assumes that the contents of the body contain a series of key / value pairs that are created (most often) by the form on the HTML side. You do not set values ​​with setHeader, as this does not put them in the body of the content.

So, with your second test, the problem you are facing is that your client does not create several key / value pairs, it only creates one and which by default was matched with the first argument in your method.

There are several options you can use. First, you can change your method to accept only one input parameter, and then pass a JSON string, as in the second test. Inside the method, you then parse the JSON string into an object that allows access to the fields.

Another option is to define a class representing the fields of the input types, and make this the only input parameter. for example

 class MyInput { String str1; String str2; public MyInput() { } // getters, setters } @POST @Consumes({"application/json"}) @Path("create/") public void create(MyInput in){ System.out.println("value 1 = " + in.getStr1()); System.out.println("value 2 = " + in.getStr2()); } 

Depending on the REST structure used, it should handle JSON de-serialization for you.

The final option is to build a POST body that looks like this:

 str1=value1&str2=value2 

then add additional annotations to your server-side method:

 public void create(@QueryParam("str1") String str1, @QueryParam("str2") String str2) 

@QueryParam does not matter if the field is in the form message or in the URL (for example, in a GET request).

If you want to continue using individual arguments in the input, then the key generates a client request to provide named request parameters either in the URL (for GET) or in the body of the POST.

+1
Nov 14 2018-11-11T14:
source