0

我正在尝试调用 RESTful Web 服务以获取 JSON 对象。现在我尝试通过 HttpGet 进行调用并成功。我需要传递的 URL 几乎是这样的:http://example.com/ /def.xxx?Name=save&Code=sample&OrderDetails=[{“Count”: “2”, “ID”: “1”, “价格”:“5”}]。我

`

StringBuilder URL = new StringBuilder("http://example.com/def.xxx?");
URL.append("Name="+name+"&");
URL.append("Code="+code+"&");
URL.append("Details=%5b");
            int val = 0;
            for (int i = 0; i<len; i++){
                    if (val > 0)
                    {URL.append(",");
                    }
                    else
                        val = 1;                
            URL.append(.....);
URLX = URL.toString();
httpGet = new HttpGet(URLX); 
response = client1.execute(httpGet);

`

现在,如果我想进行 HttpPost 调用而不是 HttpGet 调用,我该怎么办?我试过这样,

String URL = "http://example.com/def.xxx";

    DefaultHttpClient client1 = new DefaultHttpClient();
    HttpResponse response = null;
    HttpPost httpPost = new HttpPost();
    ArrayList<NameValue> postParameters;

    postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("Name", name));
        postParameters.add(new BasicNameValuePair("Code", code));

try {
            httpPost.setEntity(new UrlEncodedFormEntity(postParameters));
            } catch (UnsupportedEncodingException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }


                response = client1.execute(httpPost);

现在我不确定如何在 Post 调用中添加 Details=[{“Count”: “2”, “ID”: “1”, “Price”: “5”}] 中的值对,以及应该如何添加我执行它以获取与进行 HttpGet 调用时相同的 JSON 对象。请帮忙。

4

1 回答 1

1
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

ArrayList<NameValuePair> postParameters;

postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("Name", name));
postParameters.add(new BasicNameValuePair("Code", sample));

要构造 JSONArray 或 JSONObject 可以检查它

postParameters.add(new BasicNameValuePair("OrderDetails",jOrderdetails));

httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();

编辑:-

对于 OrderDetailsObject,您可以按如下方式构造它。

JSONArray jOrderdetails = new JSONArray();
for(int i=0;i<len;i++){
JSONObject childObject = new JSONObject();
childObject.put("Count",countvalue);
childObject.put("ID",IDvalue);
childObject.put("Price",Pricevalue);
jOrderdetails.put(childObject).toString();
}

在上面显示的方式中,您可以构造 JSONArray,然后将该对象作为参数传递。

于 2013-06-25T08:48:12.660 回答