Android使用http協議與服務器通信流程

Android使用http協議與服務器通信流程
HTTP通信類,HttpURLConnection和HttpClient。我這裏採用的是HttpClient
以下代碼是我在APP應用中修改密碼

 					new Thread() {
                            public void run() {
                                String context;
                                String path = "http://你的服務器ip/public/index.php/index/yanzmreg";
                                //傳遞服務端需要的參數
                                Map<String, String> params = new HashMap<>();
                                params.put("userName", username);
                                params.put("password", pwd);
                                try {
                                //path請求網址,params傳遞的參數
                                    context = HttpUtil.httpPost2(path, params, SetMMActivity.this);
                                    //獲取返回值
                                    JSONObject jsonObject = new JSONObject(context);
                                    int status = jsonObject.getInt("status");
                                    String msg = jsonObject.getString("msg");

                                    //判斷是否請求成功,status=1成功,否則失敗
                                    if (status==1) {
                                    //請求成功操作
                                    //獲取請求成功的返回值
                                    String data = jsonObject.getString("data");
                                        Gson gson = new Gson();
                                        Map<String, Object> map = new HashMap<String, Object>();
                                        map = gson.fromJson(data, map.getClass());
                                        id = ((Double) map.get("id")).intValue();
                                        ······
                                    }else{
                                    //請求失敗提示
                                       Looper.prepare();
                                        showToast(msg);
                                        Looper.loop();
                                        }  
                                      } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }.start();

這裏是封裝的一個網絡請求工具類,爲了避免報錯,除了請求正常並且成功的返回值其他的我都是採用提示網絡請求失敗

 public static String httpPost2(String path, Map<String, String> params, Context context) throws Exception {
        String content = null;
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            HttpParams params1 = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(params1, 10000); //設置連接超時
            HttpConnectionParams.setSoTimeout(params1, 10000); //設置請求超時
            DefaultHttpClient client = new DefaultHttpClient(params1);
            // DefaultHttpClient client = new DefaultHttpClient();
            if (params != null && !params.isEmpty()) {
                for (Map.Entry<String, String> entry : params.entrySet()) { //Map改爲對象
                    if (entry != null) {
                        pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                    } else {
                        return null;
                    }
                }
            }
            HttpPost post = new HttpPost(path);
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, "UTF-8");
            // 準備post方式提交正文 以實體形式準備(建值對形式)
            post.setEntity(entity);
            // 執行一個get請求
            HttpResponse response = client.execute(post);
            //獲取服務器的返回狀態碼
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {
                //獲取服務器返回數據 以流的形式返回
                InputStream inputStream = response.getEntity().getContent();
                // 把流轉換成字符串
                content = StreamTools.readStream(inputStream);
                //因爲有時候返回的是null,所以在這裏做了一下返回值的長度判斷
                if (content.length() < 5) {
                    return "{status:no,msg:網絡異常}";
                }
                return content;
            } else {
                return "{status:no,msg:網絡異常}";
            }
        }
    }

每次需要發送http請求時,都開一個子線程用於發送請求,子線程中接收到結果或拋出異常時,根據情況給UI線程發送message,最後在UI線程的handler的handleMessage方法中做結果解析和UI更新。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章