标签:
调试了三种通信方法:HttpClient、AsyncHttpClient 和 Volley 。
HttpClient 测试代码[1]:
public class HttpUtil { public static void sendRequestWithHttpClient(final String address, final List<NameValuePair> params, final HttpCallbackListener listener) { new Thread(new Runnable(){ @Override public void run(){ try{ HttpPost httpPost= new HttpPost(address); HttpClient httpClient = new DefaultHttpClient(); UrlEncodedFormEntity postEntity; postEntity = new UrlEncodedFormEntity(params,"utf-8"); httpPost.setEntity(postEntity); HttpResponse httpResponse = httpClient.execute(httpPost); if(httpResponse.getStatusLine().getStatusCode() == 200) { HttpEntity reEntity=httpResponse.getEntity(); String reposnse = EntityUtils.toString(reEntity,"utf-8"); if(listener != null) { listener.onFinish(reposnse); } } }catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); } }
String usertel = et_usertel.getText().toString().trim(); String password = et_password.getText().toString().trim(); String url_login = "http://192.168.1.102:8999/weixin/index.php/Home/Index/test"; List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("usertel",usertel)); params.add(new BasicNameValuePair("password",password)); HttpUtil.sendRequestWithHttpClient(url_login,params,new HttpCallbackListener(){ @Override public void onFinish(String response) { parseJSONWithJSONObject(response); } @Override public void onError(Exception e) { e.printStackTrace(); } });
private void parseJSONWithJSONObject(String jsonData){ try{ JSONArray jsonArray= new JSONArray(jsonData); Log.d("com.dlwz.playfootball","in parseJSONWithJSONObject"); for(int i=0;i<jsonArray.length();i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); String name = jsonObject.getString("usertel"); String password = jsonObject.getString("password"); Log.d("com.dlwz.playfootball","name:"+name+",password:"+password); dialog.dismiss(); startActivity(new Intent(LoginActivity.this,MainActivity.class)); } } catch(Exception e){ e.printStackTrace(); } }
AsyncHttpClient 测试代码[2] :
RequestParams params = new RequestParams(); params.put("username", email); params.put("password", password); AsyncHttpClient client = new AsyncHttpClient(); client.get("http://192.168.1.102:8081/useraccount/login/dologin",params ,new AsyncHttpResponseHandler() { // When the response returned by REST has Http response code ‘200‘ @Override public void onSuccess(String response) { // Hide Progress Dialog prgDialog.hide(); try { // JSON Object JSONObject obj = new JSONObject(response); // When the JSON response has status boolean value assigned with true if(obj.getBoolean("status")){ Toast.makeText(getApplicationContext(), "You are successfully logged in!", Toast.LENGTH_LONG).show(); // Navigate to Home screen navigatetoHomeActivity(); } // Else display error message else{ errorMsg.setText(obj.getString("error_msg")); Toast.makeText(getApplicationContext(), obj.getString("error_msg"), Toast.LENGTH_LONG).show(); } } catch (JSONException e) { // TODO Auto-generated catch block Toast.makeText(getApplicationContext(), "Error Occured [Server‘s JSON response might be invalid]!", Toast.LENGTH_LONG).show(); e.printStackTrace(); } } // When the response returned by REST has Http response code other than ‘200‘ @Override public void onFailure(int statusCode, Throwable error, String content) { // Hide Progress Dialog prgDialog.hide(); // When Http response code is ‘404‘ if(statusCode == 404){ Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show(); } // When Http response code is ‘500‘ else if(statusCode == 500){ Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show(); } // When Http response code other than 404, 500 else{ Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show(); } } });
Volley Post测试代码[3]:
RequestQueue mQueue = Volley.newRequestQueue(this); StringRequest stringRequest = new StringRequest(Request.Method.POST,"http://192.168.1.102:8999/weixin/index.php/Home/Index/test", new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d("TAG-onResponse", response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("TAG-onErrorResponse", error.getMessage(), error); } }){ @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> map = new HashMap<String, String>(); map.put("username", "mabo@qq.com"); map.put("password", "123456"); return map; } }; mQueue.add(stringRequest);
参考资料:
1、类 HttpUtil 代码参考自《第一行代码 Android》第10章5小节,只是将 HttpURLConnection 换成了 HttpClient。parseJSONWithJSONObject 参考自该书 400 页。该书作者郭霖,csdn博客:http://blog.csdn.net/guolin_blog/ 。
2、该代码参考自 http://programmerguru.com/android-tutorial/android-restful-webservice-tutorial-how-to-call-restful-webservice-in-android-part-3/?utm_source=tuicool 。该文共三部分,通过演示一个包含前端后端的例子介绍了 Restful Webservice 在 Android 开发中的应用。当时调试时 Android 端没什么问题,照着一步步来就没错,但服务器端用 Eclipse EE 创建动态web,在运行时报了错,经调试发现是在 Class.forName(Constants.dbClass) 处报了错,String dbClass = "com.mysql.jdbc.Driver" ,下载了个com.mysql.jdbc.Driver 导入才成功。
3、该代码参考自《第一行代码 Android》作者郭霖的博客:http://blog.csdn.net/guolin_blog/article/details/17482095 。测试该代码遇到了几个问题:首先就是由于防火墙的原因,volley 无法用 Git 直接 clone ,不得不设置代理才成功下载。第二个问题是 volley 的 jar 包生成,网上有不少方法,但在我这没成功。比如 stormzhang 的命令行,郭霖的通过 eclipse 导出 jar 包,可能是由于版本更新的原因,这些方法都没行,后来还是用 Android Studio 顺利编译生成 jar 包。终于可以在工程中顺利使用。第三个问题就是我自己犯的低级错误,web服务端直接用了上面AsyncHttpClient 的服务端程序,Android 端 Post 数据过去,但我没注意到服务器端只能处理 get 的 url ,因为之前用ThinkPhp 时是不用区分 get 和 post 的,处理方式一样。没想到 java 端反而要区分,耗费了不少时间才查出来。
标签:
原文地址:http://www.cnblogs.com/NaughtyBaby/p/4590399.html