我需要将一个名为"json"的json变量发送到地址通过安卓设备 http://otu-git.dyndns.ws/pvm_srv/serv.php我当前的代码是这样的:
JSONObject jsn = new JSONObject();
JSONObject json = new JSONObject();
JSONObject header = new JSONObject();
try {
header.put("txtUser", "123");
header.put("md5Passwd", "123");
header.put("fun", "validarUsuario");
jsn.put("USR", header);
json.put("json", jsn);
se = new StringEntity(json.toString());
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("json",json.toString()));
httppost.setEntity(new UrlEncodedFormEntity(params));
Log.i("dhiraj",params.toString());
////////////////////////////////////////////////////////////
HttpResponse response = httpclient.execute(httppost);
entity = response.getEntity();
但是我从服务器收到空 Json 帖子响应!
像这样添加标头
httppost.addHeader("txtUser", "123");
httppost.addHeader("md5Passwd", "123");
httppost.addHeader("fun", "fun");
注释此行 'httppost.setEntity(new UrlEncodedFormEntity(params));
否则你可以这样做
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("txtUser", "123"));
params.add(new BasicNameValuePair("md5Passwd", "123"));
params.add(new BasicNameValuePair("fun", "fun"));
httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
JSONObject jsn = new JSONObject();
JSONObject json = new JSONObject();
JSONObject header = new JSONObject();
try {
header.put("txtUser", "123");
header.put("md5Passwd", "123");
header.put("fun", "fun");
jsn.put("USR", header);
} catch (Exception e1) {
e1.printStackTrace();
}
try {
if (SDK_INT >= 10) {
ThreadPolicy tp = ThreadPolicy.LAX;
StrictMode.setThreadPolicy(tp);
}
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
// one of the method
// params.add(new BasicNameValuePair("txtUser", "123"));
// params.add(new BasicNameValuePair("md5Passwd", "123"));
// params.add(new BasicNameValuePair("fun", "fun"));
// one of the method
// // httppost.addHeader("txtUser", "123");
// // httppost.addHeader("md5Passwd", "123");
// // httppost.addHeader("fun", "fun");
HttpPost httppost = null;
httppost = new HttpPost("http://otu-git.dyndns.ws/pvm_srv/serv.php");
params.add(new BasicNameValuePair("json", jsn.toString()));
httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
Log.i("dhiraj", params.toString());
HttpClient httpclient = null;
httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String responseBody = EntityUtils.toString(response.getEntity());
String s = "";
} catch (Exception exception) {
exception.printStackTrace();
}