1. 程式人生 > >java建立HTTP請求的三種方式

java建立HTTP請求的三種方式

  目前JAVA實現HTTP請求的方法用的最多的有兩種:一種是通過HTTPClient這種第三方的開源框架去實現。HTTPClient對HTTP的封裝性比較不錯,通過它基本上能夠滿足我們大部分的需求,HttpClient3.1 是 org.apache.commons.httpclient下操作遠端 url的工具包,雖然已不再更新,但實現工作中使用httpClient3.1的程式碼還是很多,HttpClient4.5是org.apache.http.client下操作遠端 url的工具包,最新的;另一種則是通過HttpURLConnection去實現,HttpURLConnection是JAVA的標準類,是JAVA比較原生的一種實現方式。

  自己在工作中三種方式都用到過,總結一下分享給大家,也方便自己以後使用,話不多說上程式碼。

  第一種方式:java原生HttpURLConnection

複製程式碼
package com.powerX.httpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import
java.net.MalformedURLException; import java.net.URL; public class HttpClient { public static String doGet(String httpurl) { HttpURLConnection connection = null; InputStream is = null; BufferedReader br = null; String result = null;// 返回結果字串 try {
// 建立遠端url連線物件 URL url = new URL(httpurl); // 通過遠端url連線物件開啟一個連線,強轉成httpURLConnection類 connection = (HttpURLConnection) url.openConnection(); // 設定連線方式:get connection.setRequestMethod("GET"); // 設定連線主機伺服器的超時時間:15000毫秒 connection.setConnectTimeout(15000); // 設定讀取遠端返回的資料時間:60000毫秒 connection.setReadTimeout(60000); // 傳送請求 connection.connect(); // 通過connection連線,獲取輸入流 if (connection.getResponseCode() == 200) { is = connection.getInputStream(); // 封裝輸入流is,並指定字符集 br = new BufferedReader(new InputStreamReader(is, "UTF-8")); // 存放資料 StringBuffer sbf = new StringBuffer(); String temp = null; while ((temp = br.readLine()) != null) { sbf.append(temp); sbf.append("\r\n"); } result = sbf.toString(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 關閉資源 if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } connection.disconnect();// 關閉遠端連線 } return result; } public static String doPost(String httpUrl, String param) { HttpURLConnection connection = null; InputStream is = null; OutputStream os = null; BufferedReader br = null; String result = null; try { URL url = new URL(httpUrl); // 通過遠端url連線物件開啟連線 connection = (HttpURLConnection) url.openConnection(); // 設定連線請求方式 connection.setRequestMethod("POST"); // 設定連線主機伺服器超時時間:15000毫秒 connection.setConnectTimeout(15000); // 設定讀取主機伺服器返回資料超時時間:60000毫秒 connection.setReadTimeout(60000); // 預設值為:false,當向遠端伺服器傳送資料/寫資料時,需要設定為true connection.setDoOutput(true); // 預設值為:true,當前向遠端服務讀取資料時,設定為true,該引數可有可無 connection.setDoInput(true); // 設定傳入引數的格式:請求引數應該是 name1=value1&name2=value2 的形式。 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 設定鑑權資訊:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0 connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0"); // 通過連線物件獲取一個輸出流 os = connection.getOutputStream(); // 通過輸出流物件將引數寫出去/傳輸出去,它是通過位元組陣列寫出的 os.write(param.getBytes()); // 通過連線物件獲取一個輸入流,向遠端讀取 if (connection.getResponseCode() == 200) { is = connection.getInputStream(); // 對輸入流物件進行包裝:charset根據工作專案組的要求來設定 br = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuffer sbf = new StringBuffer(); String temp = null; // 迴圈遍歷一行一行讀取資料 while ((temp = br.readLine()) != null) { sbf.append(temp); sbf.append("\r\n"); } result = sbf.toString(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 關閉資源 if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != os) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } // 斷開與遠端地址url的連線 connection.disconnect(); } return result; } }
複製程式碼

  第二種方式:java原生HttpClient3.1

複製程式碼
package com.powerX.httpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class HttpClient3 {

    public static String doGet(String url) {
        // 輸入流
        InputStream is = null;
        BufferedReader br = null;
        String result = null;
        // 建立httpClient例項
        HttpClient httpClient = new HttpClient();
        // 設定http連線主機服務超時時間:15000毫秒
        // 先獲取連線管理器物件,再獲取引數物件,再進行引數的賦值
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
        // 建立一個Get方法例項物件
        GetMethod getMethod = new GetMethod(url);
        // 設定get請求超時為60000毫秒
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
        // 設定請求重試機制,預設重試次數:3次,引數設定為true,重試機制可用,false相反
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true));
        try {
            // 執行Get方法
            int statusCode = httpClient.executeMethod(getMethod);
            // 判斷返回碼
            if (statusCode != HttpStatus.SC_OK) {
                // 如果狀態碼返回的不是ok,說明失敗了,列印錯誤資訊
                System.err.println("Method faild: " + getMethod.getStatusLine());
            } else {
                // 通過getMethod例項,獲取遠端的一個輸入流
                is = getMethod.getResponseBodyAsStream();
                // 包裝輸入流
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

                StringBuffer sbf = new StringBuffer();
                // 讀取封裝的輸入流
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp).append("\r\n");
                }

                result = sbf.toString();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 關閉資源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 釋放連線
            getMethod.releaseConnection();
        }
        return result;
    }

    public static String doPost(String url, Map<String, Object> paramMap) {
        // 獲取輸入流
        InputStream is = null;
        BufferedReader br = null;
        String result = null;
        // 建立httpClient例項物件
        HttpClient httpClient = new HttpClient();
        // 設定httpClient連線主機伺服器超時時間:15000毫秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
        // 建立post請求方法例項物件
        PostMethod postMethod = new PostMethod(url);
        // 設定post請求超時時間
        postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);

        NameValuePair[] nvp = null;
        // 判斷引數map集合paramMap是否為空
        if (null != paramMap && paramMap.size() > 0) {// 不為空
            // 建立鍵值引數物件陣列,大小為引數的個數
            nvp = new NameValuePair[paramMap.size()];
            // 迴圈遍歷引數集合map
            Set<Entry<String, Object>> entrySet = paramMap.entrySet();
            // 獲取迭代器
            Iterator<Entry<String, Object>> iterator = entrySet.iterator();

            int index = 0;
            while (iterator.hasNext()) {
                Entry<String, Object> mapEntry = iterator.next();
                // 從mapEntry中獲取key和value建立鍵值物件存放到陣列中
                try {
                    nvp[index] = new NameValuePair(mapEntry.getKey(),
                            new String(mapEntry.getValue().toString().getBytes("UTF-8"), "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                index++;
            }
        }
        // 判斷nvp陣列是否為空
        if (null != nvp && nvp.length > 0) {
            // 將引數存放到requestBody物件中
            postMethod.setRequestBody(nvp);
        }
        // 執行POST方法
        try {
            int statusCode = httpClient.executeMethod(postMethod);
            // 判斷是否成功
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Method faild: " + postMethod.getStatusLine());
            }
            // 獲取遠端返回的資料
            is = postMethod.getResponseBodyAsStream();
            // 封裝輸入流
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            StringBuffer sbf = new StringBuffer();
            String temp = null;
            while ((temp = br.readLine()) != null) {
                sbf.append(temp).append("\r\n");
            }

            result = sbf.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 關閉資源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 釋放連線
            postMethod.releaseConnection();
        }
        return result;
    }
}
複製程式碼

  第三種方式:java原生httpClient4.5

複製程式碼
package com.powerX.httpClient;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClient4 {

    public static String doGet(String url) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";
        try {
            // 通過址預設配置建立一個httpClient例項
            httpClient = HttpClients.createDefault();
            // 建立httpGet遠端連線例項
            HttpGet httpGet = new HttpGet(url);
            // 設定請求頭資訊,鑑權
            httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
            // 設定配置請求引數
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 連線主機服務超時時間
                    .setConnectionRequestTimeout(35000)// 請求超時時間
                    .setSocketTimeout(60000)// 資料讀取超時時間
                    .build();
            // 為httpGet例項設定配置
            httpGet.setConfig(requestConfig);
            // 執行get請求得到返回物件
            response = httpClient.execute(httpGet);
            // 通過返回物件獲取返回資料
            HttpEntity entity = response.getEntity();
            // 通過EntityUtils中的toString方法將結果轉換為字串
            result = EntityUtils.toString(entity);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 關閉資源
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public static String doPost(String url, Map<String, Object> paramMap) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String result = "";
        // 建立httpClient例項
        httpClient = HttpClients.createDefault();
        // 建立httpPost遠端連線例項
        HttpPost httpPost = new HttpPost(url);
        // 配置請求引數例項
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 設定連線主機服務超時時間
                .setConnectionRequestTimeout(35000)// 設定連線請求超時時間
                .setSocketTimeout(60000)// 設定讀取資料連線超時時間
                .build();
        // 為httpPost例項設定配置
        httpPost.setConfig(requestConfig);
        // 設定請求頭
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        // 封裝post請求引數
        if (null != paramMap && paramMap.size() > 0) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            // 通過map整合entrySet方法獲取entity
            Set<Entry<String, Object>> entrySet = paramMap.entrySet();
            // 迴圈遍歷,獲取迭代器
            Iterator<Entry<String, Object>> iterator = entrySet.iterator();
            while (iterator.hasNext()) {
                Entry<String, Object> mapEntry = iterator.next();
                nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
            }

            // 為httpPost設定封裝好的請求引數
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        try {
            // httpClient物件執行post請求,並返回響應引數物件
            httpResponse = httpClient.execute(httpPost);
            // 從響應物件中獲取響應內容
            HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 關閉資源
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
複製程式碼

  有時候我們在使用post請求時,可能傳入的引數是json或者其他格式,此時我們則需要更改請求頭及引數的設定資訊,以httpClient4.5為例,更改下面兩列配置:httpPost.setEntity(new StringEntity("你的json串"));      httpPost.addHeader("Content-Type", "application/json")。