0

我正在制作一个应用程序,它应该在单击按钮时做出响应,例如

-- 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 
}

如何使用 http post 方法传递这些数据

4

2 回答 2

1

嗨检查这个答案:

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

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

创建如下所示的数组并将其传递给HttpPost方法。

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

该数组通过 url 传递并给你结果。

于 2013-02-21T14:07:57.153 回答
0

由于您的 Web 服务在请求中期望 JSONObject,您可以使用setEntity().

例如:

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

现在,这是一种使用请求数据调用 Web 服务的方法:

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());
 }
于 2013-02-21T14:11:43.670 回答