Android中使用HTTP和HttpClient進行通訊

qingyezhu發表於2014-11-16
/**
     * 使用HTTP的Get方式進行資料請求
     */
    protected void httpGet() {
        /**
         * 進行非同步請求
         */
        new AsyncTask<String, Void, Void>() {

            @Override
            protected Void doInBackground(String... params) {
                System.err.println("httpGet start");
                // 在此方法中只能進行資料處理,不能與進行UI互動
                try {
                    URL url = new URL(params[0]);
                    URLConnection connection = url.openConnection();
                    InputStream is = connection.getInputStream();
                    // 使用UTF-8的方式進行資料流轉化,從位元組流轉化為字元流
                    InputStreamReader isr = new InputStreamReader(is, "UTF-8");
                    BufferedReader br = new BufferedReader(isr);
                    String line = null;
                    while ((line = br.readLine()) != null) {
                        System.err.println(line);
                    }
                    // 關閉資料流
                    br.close();
                    isr.close();
                    is.close();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
        }.execute("http://fanyi.youdao.com/openapi.do?keyfrom=***&key=***&type=data&doctype=json&version=1.1&q=good");
    }

    /**
     * 使用HTTP的Post方式進行資料請求
     */
    protected void httpPost() {
        /**
         * 進行非同步請求
         */
        new AsyncTask<String, Void, Void>() {

            @Override
            protected Void doInBackground(String... params) {
                System.err.println("httpPost start");
                // 在此方法中只能進行資料處理,不能與進行UI互動
                try {
                    URL url = new URL(params[0]);
                    HttpURLConnection connection = (HttpURLConnection) url
                            .openConnection();
                    // 設定請求方式以及設定引數

                    // 設定是否向HttpURLConnection物件輸出
                    connection.setDoOutput(true);
                    // 設定請求方式
                    connection.setRequestMethod("POST");

                    // 設定引數
                    OutputStream os = connection.getOutputStream();
                    OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
                    BufferedWriter bw = new BufferedWriter(osw);
                    bw.write(params[1]);
                    bw.flush();

                    InputStream is = connection.getInputStream();
                    // 使用UTF-8的方式進行資料流轉化,從位元組流轉化為字元流
                    InputStreamReader isr = new InputStreamReader(is, "UTF-8");
                    BufferedReader br = new BufferedReader(isr);
                    String line = null;
                    while ((line = br.readLine()) != null) {
                        System.err.println(line);
                    }
                    // 關閉資料流
                    br.close();
                    isr.close();
                    is.close();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
        }.execute("http://fanyi.youdao.com/openapi.do",
                "keyfrom=***&key=***&type=data&doctype=json&version=1.1&q=good");

    }

    private HttpClient httpClient;

    /**
     * 使用HttpClient進行Get請求
     */
    protected void httpClientGet() {
        new AsyncTask<String, Void, Void>() {

            @Override
            protected Void doInBackground(String... params) {
                System.err.println("httpClientGet start");
                String urlString = params[0];
                HttpGet httpGet = new HttpGet(urlString);
                try {
                    // 傳送請求
                    HttpResponse response = httpClient.execute(httpGet);
                    // 獲取返回內容
                    String value = EntityUtils.toString(response.getEntity());
                    System.err.println(value);
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
        }.execute("http://fanyi.youdao.com/openapi.do?keyfrom=***&key=***&type=data&doctype=json&version=1.1&q=good");
    }

    /**
     * 使用HttpClient進行Post請求
     */
    protected void httpClientPost() {
        new AsyncTask<String, Void, Void>() {

            @Override
            protected Void doInBackground(String... params) {
                System.err.println("httpClientPost start");
                String urlString = params[0];
                HttpPost httpPost = new HttpPost(urlString);
                try {
                    // 設定引數
                    String[] paramsArr = params[1].split("&");
                    int len = paramsArr.length;
                    List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(
                            len);
                    BasicNameValuePair pair = null;
                    for (int i = 0; i < len; i++) {
                        String[] paramArr = paramsArr[i].split("=");
                        pair = new BasicNameValuePair(paramArr[0], paramArr[1]);
                        list.add(pair);
                    }
                    httpPost.setEntity(new UrlEncodedFormEntity(list));
                } catch (UnsupportedEncodingException e1) {
                    e1.printStackTrace();
                }

                try {
                    // 傳送請求
                    HttpResponse response = httpClient.execute(httpPost);
                    // 獲取返回內容
                    String value = EntityUtils.toString(response.getEntity());
                    System.err.println(value);
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
        }.execute("http://fanyi.youdao.com/openapi.do",
                "keyfrom=***&key=***&type=data&doctype=json&version=1.1&q=good");
    }

截圖:

 

 

 

 

 

 

相關文章