用volley访问服务器数据,不用自己额外开线程。下面例子为访问JSONObject类型的数据,具体用法看代码:
首先得有volley的jar包,如果自己没有,去github上下载,然后自己打成jar包,如果不会,可以用我的。附上jar包链接:http://download.youkuaiyun.com/detail/u010127250/8769021
RequestQueue mQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
context = this;
mQueue = Volley.newRequestQueue(context);
}
//LOGIN_PATH:String类型,访问服务器的地址 如:http://192.168.1.2:8080/mytest/LoginServlet (ip为服务器ip地址,mytest为工程名)
//dataObject:JSONObject类型,访问服务器时,给服务器传的参数,可以为null。
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(LOGIN_PATH,
dataObject, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.e("TAG", response.toString());
String result = Tools.jsonToString(response);
if (result.equals("login_success")) {
handler.sendMessage(handler.obtainMessage(2));
}
if (result.equals("password_wrong")) {
handler.sendMessage(handler.obtainMessage(1));
}
if (result.equals("usrename_null")) {
handler.sendMessage(handler.obtainMessage(0));
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
handler.sendMessage(handler.obtainMessage(-2));
}
});
mQueue.add(jsonObjectRequest);