0

i am making one application which should give response on the click of button like

-- REQUEST HEADERS --
User-Agent: XYZ
Host: root.url
Content-Type: application/json; charset=utf-8
Content-Length: 123
...

-- REQUEST BODY --
{
    "Apikey": "abcdefgh-ijkl-mnop-qrst-uvwxyz12345",
    "Imei": "0123456789012354"
    "Gps": {
        "Latitude": 1.23,
        "Longitude": 4.56
    },
    // Request specifics go here 
}

how to pass this data using http post method

jay shah
  • 29
  • 1
  • 5
  • There is a json example with android and htt client [http://stackoverflow.com/questions/6218143/android-post-json-using-http][1] [1]: http://stackoverflow.com/questions/6218143/android-post-json-using-http – Georgy Gobozov Feb 21 '13 at 14:09

2 Answers2

1

hi check this answer :

https://stackoverflow.com/a/10410693/1168654

http://localtone.blogspot.in/2009/07/post-json-using-android-and-httpclient.html

create array like below and pass it in HttpPost method.

ArrayList<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>();

nameValuePairs1.add(new BasicNameValuePair("user_id", ""));
nameValuePairs1.add(new BasicNameValuePair("product_id", ""));
nameValuePairs1.add(new BasicNameValuePair("product_review",""+text));

HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new HttpPost(URL);

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs1));

HttpResponse responce = httpclient.execute(httppost);

HttpEntity entity = responce.getEntity();

is = entity.getContent();

BufferedReader bufr = new BufferedReader(new InputStreamReader(is1,"iso-8859-1"), 8);

StringBuilder sb = new StringBuilder();

sb.append(bufr.readLine() + "\n");

String line = "0";

while ((line = bufr.readLine()) != null) 

{

sb.append(line + "\n");

}

is1.close();

result = sb.toString();

that array pass with url and give you result.

Community
  • 1
  • 1
Dhaval Parmar
  • 18,175
  • 7
  • 77
  • 170
0

As your web service expect JSONObject in a request, you can create and simple set it inside HTTPPost using setEntity().

For example:

JSONObject objRequest = new JSONObject();
objRequest.put("Apikey","abcdefgh-ijkl-mnop-qrst-uvwxyz12345");
objRequest.put("Imei","0123456789012354");

JSONObject objGps = new JSONObject();
objGps.put("Latitude",1.23);
objGps.put("Longitude",4.56);

objRequest.put(Gps, objGps);

Now, here is a way to call webservice using request data:

try{
     HttpClient httpclient = new DefaultHttpClient();
     HttpPost httpPost= new HttpPost(url);

     post.addHeader("Content-Type", "application/json; charset=utf-8");    // addHeader()    
     httpPost.setEntity(new StringEntity(objRequest.toString(),"utf-8"));  // request data

     HttpResponse response = httpclient.execute(httpPost);
     HttpEntity entity = response.getEntity();
     is = entity.getContent();
 }catch(Exception e){
      Log.e("log_tag", "Error in http connection "+e.toString());
 }
Paresh Mayani
  • 122,920
  • 69
  • 234
  • 290