android中完整的Json功能
如何通过android中完整的Json功能,android,Android,如何通过Json发送和获取请求?我正在尝试将值放入Json对象中。 我想要完整的Json教程 我不会通过Json向服务器发送请求 我正在尝试添加键/值对: jsonObjSend.put("username", "hakimfg@saifsys.com"); jsonObjSend.put("password", "abcxyz"); // Add a nested JSONObject (e.g. for header information) JSONObject header = new
Json
发送和获取请求?我正在尝试将值放入Json
对象中。我想要完整的
Json
教程我不会通过
Json
向服务器发送请求
我正在尝试添加键/值
对:
jsonObjSend.put("username", "hakimfg@saifsys.com");
jsonObjSend.put("password", "abcxyz");
// Add a nested JSONObject (e.g. for header information)
JSONObject header = new JSONObject();
header.put("deviceType","Android"); // Device type
header.put("deviceVersion","2.0"); // Device OS version
header.put("language", "es-es"); // Language of the Android client
jsonObjSend.put("header", header);
如果使用ApacheHTTP客户端,从Android发送json对象很容易。这里有一个关于如何做的代码示例。您应该为网络活动创建一个新线程,以免锁定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();
}
Android提供了几种从Android向服务器发送数据的方法。您可以使用向任何服务器发送json 片段
final String URL = "url";
HashMap<String, String> params = new HashMap<String, String>();
params.put("yourdata", "AbCdEfGh123456");
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
//update your UI
try {
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
final String URL=“URL”;
HashMap params=新的HashMap();
参数put(“yourdata”、“AbCdEfGh123456”);
JsonObjectRequest req=新JsonObjectRequest(URL,新JSONObject(参数),
新的Response.Listener(){
@凌驾
公共void onResponse(JSONObject响应){
//更新你的用户界面
试一试{
VolleyLog.v(“响应:%n%s”,响应.toString(4));
}捕获(JSONException e){
e、 printStackTrace();
}
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
e(“Error:,Error.getMessage());
}
});