我想发送以下 JSON 文本
{"Email":"aaa@tbbb.com","Password":"123456"}
到网络服务并阅读响应。我知道如何阅读 JSON。问题是上面的 JSON 对象必须以变量名 jason
的形式发送。
我怎样才能从 android 做到这一点?创建请求对象、设置内容头等步骤有哪些?
最佳答案
如果您使用 Apache HTTP 客户端,从 Android 发送 json 对象很容易。这是有关如何执行此操作的代码示例。您应该为网络 Activity 创建一个新线程,以免锁定 UI 线程。
protected void sendJson(final String email, final String pwd) {
Thread t = new Thread() {
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost(URL);
json.put("email", email);
json.put("password", pwd);
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
}
} catch(Exception e) {
e.printStackTrace();
createDialog("Error", "Cannot Estabilish Connection");
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
您也可以使用 Google Gson发送和检索 JSON。
https://stackoverflow.com/questions/3027066/