用volley訪问server数据,不用自己额外开线程。以下样例为訪问JSONObject类型的数据,详细使用方法看代码:
首先得有volley的jar包,假设自己没有。去github上下载,然后自己打成jar包,假设不会,能够用我的。附上jar包链接:http://download.csdn.net/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类型。訪问server的地址 如:http://192.168.1.2:8080/mytest/LoginServlet (ip为serverip地址,mytest为project名) //dataObject:JSONObject类型,訪问server时。给server传的參数,能够为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);
时间: 2024-11-29 01:52:26