調試了三種通訊方法:HttpClient、AsyncHttpClient 和 Volley 。php
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] :java
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]:mysql
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);
參考資料:android
一、類 HttpUtil 代碼參考自《第一行代碼 Android》第10章5小節,只是將 HttpURLConnection 換成了 HttpClient。parseJSONWithJSONObject 參考自該書 400 頁。該書做者郭霖,csdn博客:http://blog.csdn.net/guolin_blog/ 。web
二、該代碼參考自 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 導入才成功。sql
三、該代碼參考自《第一行代碼 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 端反而要區分,耗費了很多時間才查出來。json