Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use parameters with HttpPost

I am using a RESTfull webservice with this methode:

@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 app I want to call this method. How do I give the correct values to the parameters using org.apache.http.client.methods.HttpPost;

I have noticed that I can use the annotation @HeaderParam and simply add headers to the HttpPost object. Is this the correct way? Doing it like:

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

Using the setEntity methode on httpPost won't work. It only sets the parameter str1 with the json string. When using it like:

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"}  
like image 630
Klaasvaak Avatar asked Nov 14 '11 10:11

Klaasvaak


People also ask

How do I set parameters in HTTP POST?

just type your param name and value like : debug_data=1 or username_hash=jhjahbkzjxcjkahcjkzhbcjkzhbxcjshd I'm using this code with params and there is no problem for me. without annotations is the values are also null. So the problem should be in your code and the way you put the values.

How do I add parameters in HTTP request?

We can add parameters using String name-value pairs, or utilize NameValuePairs class for that purpose. Similarly, UriBuilder can be used to add parameters to other HttpClient request methods.


2 Answers

To set parameters to your 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); 
like image 134
Android-Droid Avatar answered Sep 20 '22 16:09

Android-Droid


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

(note: I have added in some extra code just incase 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(); } 
like image 44
Arthur Avatar answered Sep 20 '22 16:09

Arthur