android - 带有 JSON 字符串的 HTTP post

标签 android json web-services http-post send

我遇到了一个问题,但我不知道该如何解决。 接下来是我的问题:如何通过 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 元素。

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

最佳答案

尝试这样的事情:

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

关于android - 带有 JSON 字符串的 HTTP post,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21676550/

相关文章:

c# - 使用 Spring .NET 将用户名和密码发送到 .net Web 服务

android - 如何在android中读取fql响应

java - 即使 android.bat 存在也无法执行

asp.net - 在 SSL 上使用服务器证书时出现 HTTP 错误 403.7

json - 机器人框架 - TypeError : string indices must be integers When Parsing Json

python - 将大型 JSON 数组写入文件

java - 异步服务中的 Spring 请求范围?通过 threadLocal 变量实现 ThreadScope,加上一个 AsyncAspect 来清理

android - 喷气背包撰写 java.lang.IllegalStateException : Start/end imbalance

android - parcelable Kotlin 的 parcelable objects 列表

javascript - google.maps.InfoWindow 中的 MVC ActionLink