使用HttpClient發送Get/Post請求

背景:

通過第三方提供的restapi獲取數據

還是直接上代碼:

maven依賴:

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>2.6</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>4.5.8</version>
        </dependency>

其中httpclient是必須的,用於發送請求

commons-io是本例中使用的IOUtils的依賴,用於讀取響應流

代碼:

Get請求

public static void main(String[] args) throws IOException {
        //創建http客戶端
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //創建get請求,參數爲接口路徑,如果要加參數的話直接在url後面拼就可以了
        HttpGet httpGet = new HttpGet("http://127.0.0.1:8081/dept/list");
        //我項目裏整合了spring security,寫個header越過權限
        httpGet.setHeader("Cookie","JSESSIONID=node03q8wuwizq7ba1iafqsikravi21.node0; remember-me=cm9vdDoxNTYwNjA2NDk3MzIwOjIzNDcxNjA5N2IzNGI1OGZhYjFkYzVjNGNkY2Y2MDM2");
        //發送請求
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
        //獲取響應實體類
        HttpEntity entity = httpResponse.getEntity();
        //獲取響應內容(流)
        InputStream content = entity.getContent();
        //解析流
        String s = IOUtils.toString(content, "UTF-8");
        System.out.println(s);
    }

Post請求

public static void main(String[] args) throws IOException {
        //創建http客戶端
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //創建post請求
        HttpPost httpPost = new HttpPost("http://127.0.0.1:8081/user/delete");
        //構造請求參數,這裏也有使用json字符串+StringEntity組合的,不過好像會出現亂碼等各種問題,建議使用以下方式
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("userId", "13"));
        httpPost.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
        httpPost.setHeader("Cookie","JSESSIONID=node03q8wuwizq7ba1iafqsikravi21.node0; remember-me=cm9vdDoxNTYwNjA2NDk3MzIwOjIzNDcxNjA5N2IzNGI1OGZhYjFkYzVjNGNkY2Y2MDM2");
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();
        String s = IOUtils.toString(content, "UTF-8");
        System.out.println(s);

    }

 

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