1. 程式人生 > 實用技巧 >2018-2019 ICPC Northwestern European Regional Programming Contest (NWERC 2018)

2018-2019 ICPC Northwestern European Regional Programming Contest (NWERC 2018)

簡介

  HTTP 協議可能是現在 Internet 上使用得最多、最重要的協議了,越來越多的 Java 應用程式需要直接通過 HTTP 協議來訪問網路資源。雖然在 JDK 的 java.net 包中已經提供了訪問 HTTP 協議的基本功能,但是對於大部分應用程式來說,JDK 庫本身提供的功能還不夠豐富和靈活。HttpClient 是 Apache Jakarta Common 下的子專案,用來提供高效的、最新的、功能豐富的支援 HTTP 協議的客戶端程式設計工具包,並且它支援 HTTP 協議最新的版本和建議。

HTTP 和瀏覽器有點像,但卻不是瀏覽器。很多人覺得既然 HttpClient 是一個 HTTP 客戶端程式設計工具,很多人把他當做瀏覽器來理解,但是其實 HttpClient 不是瀏覽器,它是一個 HTTP 通訊庫,因此它只提供一個通用瀏覽器應用程式所期望的功能子集,最根本的區別是 HttpClient 中沒有使用者介面,瀏覽器需要一個渲染引擎來顯示頁面,並解釋使用者輸入,例如滑鼠點選顯示頁面上的某處,有一個佈局引擎,計算如何顯示 HTML 頁面,包括級聯樣式表和影象。javascript 直譯器執行嵌入 HTML 頁面或從 HTML 頁面引用的 javascript 程式碼。來自使用者介面的事件被傳遞到 javascript 直譯器進行處理。除此之外,還有用於外掛的介面,可以處理 Applet,嵌入式媒體物件(如 pdf 檔案,Quicktime 電影和 Flash 動畫)或 ActiveX 控制元件(可以執行任何操作)。HttpClient 只能以程式設計的方式通過其 API 用於傳輸和接受 HTTP 訊息。

HttpClient 的主要功能:

  • 實現了所有 HTTP 的方法(GET、POST、PUT、HEAD、DELETE、HEAD、OPTIONS 等)
  • 支援 HTTPS 協議
  • 支援代理伺服器(Nginx 等)等
  • 支援自動(跳轉)轉向
  • ……

環境說明:JDK1.8、SpringBoot

準備環節

引入依賴

<!-- fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <
version>1.2.47</version> </dependency> <!-- httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.5</version> </dependency>

注意:

  • 本人引入此依賴的目的是,在後續示例中,會用到“將物件轉化為 json 字串的功能”,也可以引其他有此功能的依賴。
  • SpringBoot 的基本依賴配置,這裡就不再多說了。

詳細使用示例

宣告:此示例中,以 JAVA 傳送 HttpClient(在 test 裡面單元測試傳送的);也是以 JAVA 接收的(在 controller 裡面接收的)。

宣告:下面的程式碼,本人親測有效。注意:函式中的異常沒有捕獲,正常情況需要捕獲,且資源關閉需要放到 finally 中。

GET 無參

HttpClient 傳送示例:

/**
 * GET---無參測試
 */
@Test
public void doGetTestOne() throws Exception {
    // 獲得Http客戶端(可以理解為:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    // 建立Get請求
    HttpGet httpGet = new HttpGet("http://127.0.0.1:8888/doGetControllerOne");

    // 響應模型
    CloseableHttpResponse response = httpClient.execute(httpGet);// 由客戶端執行(傳送)Get請求
    // 從響應模型中獲取響應實體
    HttpEntity responseEntity = response.getEntity();
    System.out.println("響應狀態為:" + response.getStatusLine());
    if (responseEntity != null) {
        System.out.println("響應內容長度為:" + responseEntity.getContentLength());
        System.out.println("響應內容為:" + EntityUtils.toString(responseEntity));
    }
    if (response != null) {
        response.close();
    }
    // 釋放資源
    if (httpClient != null) {
        httpClient.close();
    }
}

接收示例:

/**
 * GET無參
 */
@RequestMapping("/doGetControllerOne")
public String doGetControllerOne() {
    return "123";
}

控制檯列印:

響應狀態為:HTTP/1.1 200 
響應內容長度為:3
響應內容為:123

GET有參(方式一:直接拼接URL)

HttpClient 傳送示例:

/**
 * GET---有參測試 (方式一:手動在url後面加上引數)
 */
@Test
public void doGetTestWayOne() throws Exception {
    // 獲得Http客戶端(可以理解為:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();

    // 引數
    StringBuilder params = new StringBuilder();
    // 字元資料最好encoding以下;這樣一來,某些特殊字元才能傳過去(如:某人的名字就是“&”,不encoding的話,傳不過去)
    params.append("name=").append(URLEncoder.encode("張三", "utf-8"));
    params.append("&");
    params.append("age=24");

    // 建立Get請求
    HttpGet httpGet = new HttpGet("http://localhost:8888/doGetControllerTwo" + "?" + params);
    // 響應模型
    CloseableHttpResponse response = null;
    // 配置資訊
    RequestConfig requestConfig = RequestConfig.custom()
            // 設定連線超時時間(單位毫秒)
            .setConnectTimeout(5000)
            // 設定請求超時時間(單位毫秒)
            .setConnectionRequestTimeout(5000)
            // socket讀寫超時時間(單位毫秒)
            .setSocketTimeout(5000)
            // 設定是否允許重定向(預設為true)
            .setRedirectsEnabled(true).build();

    // 將上面的配置資訊 運用到這個Get請求裡
    httpGet.setConfig(requestConfig);

    // 由客戶端執行(傳送)Get請求
    response = httpClient.execute(httpGet);
    // 從響應模型中獲取響應實體
    HttpEntity responseEntity = response.getEntity();
    System.out.println("響應狀態為:" + response.getStatusLine());
    if (responseEntity != null) {
        System.out.println("響應內容長度為:" + responseEntity.getContentLength());
        System.out.println("響應內容為:" + EntityUtils.toString(responseEntity));
    }
    if (response != null) {
        response.close();
    }
    // 釋放資源
    if (httpClient != null) {
        httpClient.close();
    }
}

接收示例:

/**
 * GET有參
 */
@RequestMapping("/doGetControllerTwo")
public String doGetControllerTwo(String name, Integer age) {
    return "沒想到[" + name + "]都" + age + "歲了!";
}

控制檯列印:

響應狀態為:HTTP/1.1 200 
響應內容長度為:29
響應內容為:沒想到[張三]都24歲了!

GET 有參(方式二:使用 URI 獲得 HttpGet)

HttpClient 傳送示例:

/**
 * GET---有參測試 (方式二:將引數放入鍵值對類中,再放入URI中,從而通過URI得到HttpGet例項)
 */
@Test
public void doGetTestWayTwo() throws Exception {
    // 獲得Http客戶端(可以理解為:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();

    // 引數
    URI uri = null;
    // 將引數放入鍵值對類NameValuePair中,再放入集合中
    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("name", "&"));
    params.add(new BasicNameValuePair("age", "18"));
    // 設定uri資訊,並將引數集合放入uri;
    // 注:這裡也支援一個鍵值對一個鍵值對地往裡面放setParameter(String key, String value)
    uri = new URIBuilder().setScheme("http").setHost("localhost")
            .setPort(8888).setPath("/doGetControllerTwo")
            .setParameters(params).build();
    // 建立Get請求
    HttpGet httpGet = new HttpGet(uri);

    // 響應模型
    CloseableHttpResponse response = null;
    // 配置資訊
    RequestConfig requestConfig = RequestConfig.custom()
            // 設定連線超時時間(單位毫秒)
            .setConnectTimeout(5000)
            // 設定請求超時時間(單位毫秒)
            .setConnectionRequestTimeout(5000)
            // socket讀寫超時時間(單位毫秒)
            .setSocketTimeout(5000)
            // 設定是否允許重定向(預設為true)
            .setRedirectsEnabled(true).build();

    // 將上面的配置資訊 運用到這個Get請求裡
    httpGet.setConfig(requestConfig);

    // 由客戶端執行(傳送)Get請求
    response = httpClient.execute(httpGet);
    // 從響應模型中獲取響應實體
    HttpEntity responseEntity = response.getEntity();
    System.out.println("響應狀態為:" + response.getStatusLine());
    if (responseEntity != null) {
        System.out.println("響應內容長度為:" + responseEntity.getContentLength());
        System.out.println("響應內容為:" + EntityUtils.toString(responseEntity));
    }
    // 釋放資源
    if (httpClient != null) {
        httpClient.close();
    }
    if (response != null) {
        response.close();
    }
}

接收示例:同上

控制檯列印:

響應狀態為:HTTP/1.1 200 
響應內容長度為:24
響應內容為:沒想到[&]都18歲了!

POST 無參

HttpClient 傳送示例:

/**
 * POST---無參測試
 */
@Test
public void doPostTestOne() throws Exception {

    // 獲得Http客戶端(可以理解為:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)
    CloseableHttpClient httpClient = HttpClients.createDefault();

    // 建立Post請求
    HttpPost httpPost = new HttpPost("http://localhost:8888/doPostControllerOne");
    // 響應模型
    CloseableHttpResponse response = httpClient.execute(httpPost);// 由客戶端執行(傳送)Post請求
    // 從響應模型中獲取響應實體
    HttpEntity responseEntity = response.getEntity();

    System.out.println("響應狀態為:" + response.getStatusLine());
    if (responseEntity != null) {
        System.out.println("響應內容長度為:" + responseEntity.getContentLength());
        System.out.println("響應內容為:" + EntityUtils.toString(responseEntity));
    }

    // 釋放資源
    if (response != null) {
        response.close();
    }
    if (httpClient != null) {
        httpClient.close();
    }
}

接收示例:

/**
 * POST無參
 */
@RequestMapping(value = "/doPostControllerOne", method = RequestMethod.POST)
public String doPostControllerOne() {
    return "這個post請求沒有任何引數!";
}

控制檯列印:

響應狀態為:HTTP/1.1 200 
響應內容長度為:35
響應內容為:這個post請求沒有任何引數!

POST 有參(普通引數,方式一:直接拼接URL)

注:POST 傳遞普通引數時,方式與 GET 一樣即可,這裡以直接在 url 字尾上引數的方式示例。

HttpClient 傳送示例:

/**
 * POST---有參測試(基本引數)
 */
@Test
public void doPostTestFour() throws Exception {
    // 獲得Http客戶端(可以理解為:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();

    // 引數
    StringBuilder params = new StringBuilder();
    // 字元資料最好encoding以下;這樣一來,某些特殊字元才能傳過去(如:某人的名字就是“&”,不encoding的話,傳不過去)
    params.append("name=").append(URLEncoder.encode("&", "utf-8"));
    params.append("&");
    params.append("age=24");

    // 建立Post請求
    HttpPost httpPost = new HttpPost("http://localhost:8888/doPostControllerFour" + "?" + params);

    // 設定ContentType(注:如果只是傳普通引數的話,ContentType不一定非要用application/json)
    httpPost.setHeader("Content-Type", "application/json;charset=utf8");

    // 響應模型
    CloseableHttpResponse response = null;
    // 由客戶端執行(傳送)Post請求
    response = httpClient.execute(httpPost);
    // 從響應模型中獲取響應實體
    HttpEntity responseEntity = response.getEntity();

    System.out.println("響應狀態為:" + response.getStatusLine());
    if (responseEntity != null) {
        System.out.println("響應內容長度為:" + responseEntity.getContentLength());
        System.out.println("響應內容為:" + EntityUtils.toString(responseEntity));
    }

    // 釋放資源
    if (response != null) {
        response.close();
    }
    if (httpClient != null) {
        httpClient.close();
    }
}

接收示例:

/**
 * POST有參(普通引數)
 */
@RequestMapping(value = "/doPostControllerFour", method = RequestMethod.POST)
public String doPostControllerThree1(String name, Integer age) {
    return "[" + name + "]居然才[" + age + "]歲!!!";
}

控制檯列印:

響應狀態為:HTTP/1.1 200 
響應內容長度為:22
響應內容為:[&]居然才[24]歲!!!

POST 有參(普通引數,方式二:setEntity)

/**
 * POST有參(普通引數)
 */
@Test
public void doPostTestFour2() throws Exception {
    // 建立預設的httpClient例項.
    CloseableHttpClient httpClient = HttpClients.createDefault();
    // 建立httppost
    HttpPost httppost = new HttpPost("http://localhost:8888/doPostControllerFour");
    // 建立引數佇列
    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("name", "&"));
    formparams.add(new BasicNameValuePair("age", "24"));
    UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");

    httppost.setEntity(uefEntity);
    System.out.println("executing request " + httppost.getURI());
    CloseableHttpResponse response = httpClient.execute(httppost);
    HttpEntity responseEntity = response.getEntity();
    System.out.println("響應狀態為:" + response.getStatusLine());
    if (responseEntity != null) {
        System.out.println("響應內容長度為:" + responseEntity.getContentLength());
        System.out.println("響應內容為:" + EntityUtils.toString(responseEntity));
    }

    // 釋放資源
    if (response != null) {
        response.close();
    }
    if (httpClient != null) {
        httpClient.close();
    }
}

接收示例和控制檯列印同上

POST 有參(物件引數)

先給出 User 類

/**
 * 使用者實體類模型
 */
public class User {

    /**
     * 姓名
     */
    private String name;

    /**
     * 年齡
     */
    private Integer age;

    /**
     * 性別
     */
    private String gender;

    /**
     * 座右銘
     */
    private String motto;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getMotto() {
        return motto;
    }

    public void setMotto(String motto) {
        this.motto = motto;
    }

    @Override
    public String toString() {
        return age + "歲" + gender + "人[" + name + "]的座右銘居然是: " + motto + "!!!";
    }

}
User 類

HttpClient 傳送示例:

/**
 * POST---有參測試(物件引數)
 */
@Test
public void doPostTestTwo() throws Exception {

    // 獲得Http客戶端(可以理解為:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();

    // 建立Post請求
    HttpPost httpPost = new HttpPost("http://localhost:8888/doPostControllerTwo");
    User user = new User();
    user.setName("潘曉婷");
    user.setAge(18);
    user.setGender("女");
    user.setMotto("姿勢要優雅~");
    // 我這裡利用阿里的fastjson,將Object轉換為json字串;
    // (需要匯入com.alibaba.fastjson.JSON包)
    String jsonString = JSON.toJSONString(user);

    StringEntity entity = new StringEntity(jsonString, "UTF-8");

    // post請求是將引數放在請求體裡面傳過去的;這裡將entity放入post請求體中
    httpPost.setEntity(entity);

    httpPost.setHeader("Content-Type", "application/json;charset=utf8");

    // 響應模型
    CloseableHttpResponse response = httpClient.execute(httpPost);// 由客戶端執行(傳送)Post請求
    // 從響應模型中獲取響應實體
    HttpEntity responseEntity = response.getEntity();

    System.out.println("響應狀態為:" + response.getStatusLine());
    if (responseEntity != null) {
        System.out.println("響應內容長度為:" + responseEntity.getContentLength());
        System.out.println("響應內容為:" + EntityUtils.toString(responseEntity));
    }
    // 釋放資源
    if (response != null) {
        response.close();
    }
    if (httpClient != null) {
        httpClient.close();
    }
}

接收示例:

/**
 * POST有參(物件引數)
 */
@RequestMapping(value = "/doPostControllerTwo", method = RequestMethod.POST)
public String doPostControllerTwo(@RequestBody User user) {
    return user.toString();
}

控制檯列印:

響應狀態為:HTTP/1.1 200 
響應內容長度為:64
響應內容為:18歲女人[潘曉婷]的座右銘居然是: 姿勢要優雅~!!!

POST 有參(普通引數 + 物件引數)

注:POST 傳遞普通引數時,方式與 GET 一樣即可,這裡以通過 URI 獲得 HttpPost 的方式為例。

HttpClient 傳送示例:

/**
 * POST---有參測試(普通引數 + 物件引數)
 */
@Test
public void doPostTestThree() throws Exception {

    // 獲得Http客戶端(可以理解為:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();

    // 建立Post請求
    // 引數
    URI uri = null;
    // 將引數放入鍵值對類NameValuePair中,再放入集合中
    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("flag", "4"));
    params.add(new BasicNameValuePair("meaning", "這是什麼鬼?"));
    // 設定uri資訊,並將引數集合放入uri;
    // 注:這裡也支援一個鍵值對一個鍵值對地往裡面放setParameter(String key, String value)
    uri = new URIBuilder().setScheme("http").setHost("localhost").setPort(8888)
            .setPath("/doPostControllerThree").setParameters(params).build();


    HttpPost httpPost = new HttpPost(uri);

    // 建立user引數
    User user = new User();
    user.setName("潘曉婷");
    user.setAge(18);
    user.setGender("女");
    user.setMotto("姿勢要優雅~");

    // 將user物件轉換為json字串,並放入entity中
    StringEntity entity = new StringEntity(JSON.toJSONString(user), "UTF-8");

    // post請求是將引數放在請求體裡面傳過去的;這裡將entity放入post請求體中
    httpPost.setEntity(entity);

    httpPost.setHeader("Content-Type", "application/json;charset=utf8");

    // 響應模型
    CloseableHttpResponse response = null;
    // 由客戶端執行(傳送)Post請求
    response = httpClient.execute(httpPost);
    // 從響應模型中獲取響應實體
    HttpEntity responseEntity = response.getEntity();

    System.out.println("響應狀態為:" + response.getStatusLine());
    if (responseEntity != null) {
        System.out.println("響應內容長度為:" + responseEntity.getContentLength());
        System.out.println("響應內容為:" + EntityUtils.toString(responseEntity));
    }

    // 釋放資源
    if (response != null) {
        response.close();
    }
    if (httpClient != null) {
        httpClient.close();
    }
}

接收示例:

/**
 * POST有參(普通引數 + 物件引數)
 */
@RequestMapping(value = "/doPostControllerThree", method = RequestMethod.POST)
public String doPostControllerThree(@RequestBody User user,Integer flag, String meaning) {
    return user.toString() + "\n" + flag + ">>>" + meaning;
}

控制檯列印:

響應狀態為:HTTP/1.1 200 
響應內容長度為:87
響應內容為:18歲女人[潘曉婷]的座右銘居然是: 姿勢要優雅~!!!
4>>>這是什麼鬼?

本文轉載自:https://blog.csdn.net/justry_deng/article/details/81042379

參考:https://blog.csdn.net/w372426096/article/details/82713315