我是android的新手我尝试使用JSON将POST方法发送到PHP我发送的数据不会出现在PHP中,在PHP中发布的请求但是当我尝试读取POST数据时我有数组null。
protected void sendJson(final String username, final String password) {
Thread t = new Thread() {
public void run() {
Looper.prepare();
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
JSONObject json = new JSONObject();
String URL = "MY_URL";
try {
HttpPost post = new HttpPost(URL);
json.put("section", "API");
json.put("username", username);
json.put("password", password);
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
if(response!=null)
{
String result = EntityUtils.toString(response.getEntity());
Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
//InputStream in = response.getEntity().getContent(); //Get the data in the entity
}
} catch(Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Cannot Estabilish Connection", Toast.LENGTH_LONG).show();
}
Looper.loop();
}
};
t.start();
}
答案 0 :(得分:0)
尝试accumulate
代替put
:
json.accumulate("section", "API");
json.accumulate("username", username);
json.accumulate("password", password);
尝试使用此方法设置标题:
post.setEntity(se);
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
如果你也想看看Gson API。它有助于解析...这是一个很好的tuto。