【问题标题】:HTTP post with JSON string带有 JSON 字符串的 HTTP 帖子
【发布时间】:2014-03-07 17:53:33
【问题描述】:

我有一个问题,我不知道该如何解决。 接下来是我的问题:如何通过 Httpost 发送:data={"value":0, "list":[]} 我尝试以字符串形式发送此 data={"value":0, "list":[]} 但我只获得,您需要来自服务器的 POST 值。

这是我的代码:

        HttpParams params = new BasicHttpParams();
        //params.setParameter("data", auth);
        HttpClient httpclient = new DefaultHttpClient(params);

        JSONObject auth = new JSONObject(); 
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        List<NameValuePair> nameValueP = new ArrayList<NameValuePair>(2);
        ArrayList<String> aList = new ArrayList<String>();
        nameValuePairs.add(new BasicNameValuePair("value", "0"));
        nameValuePairs.add(new BasicNameValuePair("list", aList.toString()));
        nameValueP.add(new BasicNameValuePair("data", nameValuePairs.get(0).toString()+nameValuePairs.get(1).toString()));

        HttpPost httpPost = new HttpPost(url);

        httpPost.setHeader("Content-type", "application/json");


        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        entity.setContentEncoding(HTTP.UTF_8);

        HttpResponse response = httpclient.execute(httpPost);
        HttpEntity entities = response.getEntity();               

        String outPut = EntityUtils.toString(entities);

outPut 返回错误,此错误表示我需要从服务器发送 POST 元素。

这段代码应该返回一个列表,这个列表是一个包含不同元素的数组。

【问题讨论】:

  • 因为这个问题出现在我的安卓应用中。

标签: android json web-services http-post send


【解决方案1】:

试试这样的:

            JSONObject jsonParams = new JSONObject();
    try {

        JSONObject jsComm = new JSONObject();
        JSONObject jsLoc = new JSONObject();
        jsLoc.put("lat", (float) lat);
        jsLoc.put("long", (float) lng);
        jsComm.put("location", jsLoc);
        jsComm.put("text", txt);
        jsonParams.put("comment", jsComm);
    } catch (JSONException e2) {
        Log.d("exception", "Exception while parsing json array :" + e2.toString());
        e2.printStackTrace();
    }

然后使用:

AbstractHttpEntity entity = null;
entity = new ByteArrayEntity(jsonParams.toString().getBytes("UTF8"));
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(entity);

【讨论】:

    猜你喜欢
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多