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