我在Android中使用HttpPost调用webservice post请求我有一个json数组,它的工作正常,但是当我传递一个JsonArray时,它不能工作 任何建议将不胜感激
像这样 JSONObject jo=new JSONObject();
jo.put("title","some string value");
jo.put("players","[1,2,3]");
HttpResponse rr= makeRequest(url,jo.toString());
json_string = EntityUtils.toString(rr.getEntity());
///我的请求功能
public HttpResponse makeRequest(String uri, String json) {
try {
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(new StringEntity(json));
SharedPreferences sf=this.getSharedPreferences("all", 0);
String authToken=sf.getString("authToken","");
httpPost.setHeader("authtoken", authToken);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
return new DefaultHttpClient().execute(httpPost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
答案 0 :(得分:0)
使用此
try {
JSONObject json = new JSONObject();
json.put("UserName", "test2");
json.put("FullName", "1234567");
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);
//
//String url = "http://10.0.2.2:8080/sample1/webservice2.php?" +
// "json={\"UserName\":1,\"FullName\":2}";
String url = "http://10.0.2.2:8080/sample1/webservice2.php";
HttpPost request = new HttpPost(url);
request.setEntity(new ByteArrayEntity(json.toString().getBytes(
"UTF8")));
request.setHeader("json", json.toString());
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
Log.i("Read from server", result);
Toast.makeText(this, result,
Toast.LENGTH_LONG).show();
}
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}