Klaasvaak Klaasvaak - 1 year ago 79
JSON Question

How to use parameters with HttpPost

I am using a RESTfull webservice with this methode:

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());
//server output: value 1 = {"str1":"a value","str2":"another value"}

Answer Source

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));

    HttpResponse response = httpclient.execute(httppost);