httpclient

    1. 什麼是httpclient

HTTP 協議多是如今 Internet 上使用得最多、最重要的協議了,愈來愈多的 Java 應用程序須要直接經過 HTTP 協議來訪問網絡資源。雖然在 JDK java net包中已經提供了訪問 HTTP 協議的基本功能,可是對於大部分應用程序來講,JDK 庫自己提供的功能還不夠豐富和靈活。HttpClient Apache Jakarta Common 下的子項目,用來提供高效的、最新的、功能豐富的支持 HTTP 協議的客戶端編程工具包,而且它支持 HTTP 協議最新的版本和建議。
下載地址:html

http://hc.apache.org/java

 

2.apache

功能介紹編程

 

如下列出的是 HttpClient 提供的主要的功能,要知道更多詳細的功能能夠參見 HttpClient 的主頁。服務器

1)實現了全部 HTTP 的方法(GET,POST,PUT,HEAD 等)網絡

2)支持自動轉向ide

3)支持 HTTPS 協議工具

4)支持代理服務器等post

 

 

 

導入依賴ui

 

 

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.3.5</version>
</dependency>

 

 

 

 

執行GET請求

 

public class DoGET {

    public static void main(String[] args) throws Exception {

        // 建立Httpclient對象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 建立http GET請求
        HttpGet httpGet = new HttpGet("http://www.baidu.com/");

        CloseableHttpResponse response = null;
        try {
            // 執行請求
            response = httpclient.execute(httpGet);
            // 判斷返回狀態是否爲200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println("內容長度:" + content.length());
//                FileUtils.writeStringToFile(new File("C:\\baidu.html"), content);
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }

    }

}

 

 

執行GET帶參數

 

public class DoGETParam {

    public static void main(String[] args) throws Exception {

        // 建立Httpclient對象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 定義請求的參數
        URI uri = new URIBuilder("http://www.baidu.com/s").setParameter("wd", "java").build();

        System.out.println(uri);

        // 建立http GET請求
        HttpGet httpGet = new HttpGet(uri);

        CloseableHttpResponse response = null;
        try {
            // 執行請求
            response = httpclient.execute(httpGet);
            // 判斷返回狀態是否爲200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(content);
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }

    }

}

 

 

執行post請求

 

public class DoPOST {

    public static void main(String[] args) throws Exception {

        // 建立Httpclient對象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 建立http POST請求
        HttpPost httpPost = new HttpPost("http://www.oschina.net/");

        CloseableHttpResponse response = null;
        try {
            // 執行請求
            response = httpclient.execute(httpPost);
            // 判斷返回狀態是否爲200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(content);
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }

    }

}

 

帶參數的post請求

 

public class DoPOSTParam {

    public static void main(String[] args) throws Exception {

        // 建立Httpclient對象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 建立http POST請求
        HttpPost httpPost = new HttpPost("http://www.oschina.net/search");

        // 設置2個post參數,一個是scope、一個是q
        List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
        parameters.add(new BasicNameValuePair("scope", "project"));
        parameters.add(new BasicNameValuePair("q", "java"));
        // 構造一個form表單式的實體
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
        // 將請求實體設置到httpPost對象中
        httpPost.setEntity(formEntity);

        CloseableHttpResponse response = null;
        try {
            // 執行請求
            response = httpclient.execute(httpPost);
            // 判斷返回狀態是否爲200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(content);
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }

    }

}

 

封裝HttpClient通用工具類

 

public class HttpClientUtil {

    public static String doGet(String url, Map<String, String> param) {

        // 建立Httpclient對象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 建立uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 建立http GET請求
            HttpGet httpGet = new HttpGet(uri);

            // 執行請求
            response = httpclient.execute(httpGet);
            // 判斷返回狀態是否爲200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, null);
    }

    public static String doPost(String url, Map<String, String> param) {
        // 建立Httpclient對象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 建立Http Post請求
            HttpPost httpPost = new HttpPost(url);
            // 建立參數列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模擬表單
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            // 執行http請求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String doPost(String url) {
        return doPost(url, null);
    }
}
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息