HttpClient調(diào)用

GET無參

 /**
     * GET---無參測(cè)試
     *
     * @date 2018年7月13日 下午4:18:50
     */
    @Test
    public void doGetTestOne() {
        // 獲得Http客戶端(可以理解為:你得先有一個(gè)瀏覽器;注意:實(shí)際上HttpClient與瀏覽器是不一樣的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 創(chuàng)建Get請(qǐng)求
        HttpGet httpGet = new HttpGet("http://localhost:12345/doGetControllerOne");
 
        // 響應(yīng)模型
        CloseableHttpResponse response = null;
        try {
            // 由客戶端執(zhí)行(發(fā)送)Get請(qǐng)求
            response = httpClient.execute(httpGet);
            // 從響應(yīng)模型中獲取響應(yīng)實(shí)體
            HttpEntity responseEntity = response.getEntity();
            System.out.println("響應(yīng)狀態(tài)為:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("響應(yīng)內(nèi)容長度為:" + responseEntity.getContentLength());
                System.out.println("響應(yīng)內(nèi)容為:" + EntityUtils.toString(responseEntity));
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 釋放資源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

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

/**
     * GET---有參測(cè)試 (方式一:手動(dòng)在url后面加上參數(shù))
     *
     * @date 2018年7月13日 下午4:19:23
     */
    @Test
    public void doGetTestWayOne() {
        // 獲得Http客戶端(可以理解為:你得先有一個(gè)瀏覽器;注意:實(shí)際上HttpClient與瀏覽器是不一樣的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
 
        // 參數(shù)
        StringBuffer params = new StringBuffer();
        try {
            // 字符數(shù)據(jù)最好encoding以下;這樣一來,某些特殊字符才能傳過去(如:某人的名字就是“&”,不encoding的話,傳不過去)
            params.append("name=" + URLEncoder.encode("&", "utf-8"));
            params.append("&");
            params.append("age=24");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
 
        // 創(chuàng)建Get請(qǐng)求
        HttpGet httpGet = new HttpGet("http://localhost:12345/doGetControllerTwo" + "?" + params);
        // 響應(yīng)模型
        CloseableHttpResponse response = null;
        try {
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 設(shè)置連接超時(shí)時(shí)間(單位毫秒)
                    .setConnectTimeout(5000)
                    // 設(shè)置請(qǐng)求超時(shí)時(shí)間(單位毫秒)
                    .setConnectionRequestTimeout(5000)
                    // socket讀寫超時(shí)時(shí)間(單位毫秒)
                    .setSocketTimeout(5000)
                    // 設(shè)置是否允許重定向(默認(rèn)為true)
                    .setRedirectsEnabled(true).build();
 
            // 將上面的配置信息 運(yùn)用到這個(gè)Get請(qǐng)求里
            httpGet.setConfig(requestConfig);
 
            // 由客戶端執(zhí)行(發(fā)送)Get請(qǐng)求
            response = httpClient.execute(httpGet);
 
            // 從響應(yīng)模型中獲取響應(yīng)實(shí)體
            HttpEntity responseEntity = response.getEntity();
            System.out.println("響應(yīng)狀態(tài)為:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("響應(yīng)內(nèi)容長度為:" + responseEntity.getContentLength());
                System.out.println("響應(yīng)內(nèi)容為:" + EntityUtils.toString(responseEntity));
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 釋放資源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

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

 /**
     * GET---有參測(cè)試 (方式二:將參數(shù)放入鍵值對(duì)類中,再放入U(xiǎn)RI中,從而通過URI得到HttpGet實(shí)例)
     *
     * @date 2018年7月13日 下午4:19:23
     */
    @Test
    public void doGetTestWayTwo() {
        // 獲得Http客戶端(可以理解為:你得先有一個(gè)瀏覽器;注意:實(shí)際上HttpClient與瀏覽器是不一樣的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
 
        // 參數(shù)
        URI uri = null;
        try {
            // 將參數(shù)放入鍵值對(duì)類NameValuePair中,再放入集合中
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("name", "&"));
            params.add(new BasicNameValuePair("age", "18"));
            // 設(shè)置uri信息,并將參數(shù)集合放入uri;
            // 注:這里也支持一個(gè)鍵值對(duì)一個(gè)鍵值對(duì)地往里面放setParameter(String key, String value)
            uri = new URIBuilder().setScheme("http").setHost("localhost")
                                  .setPort(12345).setPath("/doGetControllerTwo")
                                  .setParameters(params).build();
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
        }
        // 創(chuàng)建Get請(qǐng)求
        HttpGet httpGet = new HttpGet(uri);
 
        // 響應(yīng)模型
        CloseableHttpResponse response = null;
        try {
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 設(shè)置連接超時(shí)時(shí)間(單位毫秒)
                    .setConnectTimeout(5000)
                    // 設(shè)置請(qǐng)求超時(shí)時(shí)間(單位毫秒)
                    .setConnectionRequestTimeout(5000)
                    // socket讀寫超時(shí)時(shí)間(單位毫秒)
                    .setSocketTimeout(5000)
                    // 設(shè)置是否允許重定向(默認(rèn)為true)
                    .setRedirectsEnabled(true).build();
 
            // 將上面的配置信息 運(yùn)用到這個(gè)Get請(qǐng)求里
            httpGet.setConfig(requestConfig);
 
            // 由客戶端執(zhí)行(發(fā)送)Get請(qǐng)求
            response = httpClient.execute(httpGet);
 
            // 從響應(yīng)模型中獲取響應(yīng)實(shí)體
            HttpEntity responseEntity = response.getEntity();
            System.out.println("響應(yīng)狀態(tài)為:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("響應(yīng)內(nèi)容長度為:" + responseEntity.getContentLength());
                System.out.println("響應(yīng)內(nèi)容為:" + EntityUtils.toString(responseEntity));
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 釋放資源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

POST無參


    /**
     * POST---無參測(cè)試
     *
     * @date 2018年7月13日 下午4:18:50
     */
    @Test
    public void doPostTestOne() {
 
        // 獲得Http客戶端(可以理解為:你得先有一個(gè)瀏覽器;注意:實(shí)際上HttpClient與瀏覽器是不一樣的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
 
        // 創(chuàng)建Post請(qǐng)求
        HttpPost httpPost = new HttpPost("http://localhost:12345/doPostControllerOne");
        // 響應(yīng)模型
        CloseableHttpResponse response = null;
        try {
            // 由客戶端執(zhí)行(發(fā)送)Post請(qǐng)求
            response = httpClient.execute(httpPost);
            // 從響應(yīng)模型中獲取響應(yīng)實(shí)體
            HttpEntity responseEntity = response.getEntity();
 
            System.out.println("響應(yīng)狀態(tài)為:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("響應(yīng)內(nèi)容長度為:" + responseEntity.getContentLength());
                System.out.println("響應(yīng)內(nèi)容為:" + EntityUtils.toString(responseEntity));
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 釋放資源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

POST有參(普通參數(shù))

 /**
     * POST---有參測(cè)試(普通參數(shù))
     *
     * @date 2018年7月13日 下午4:18:50
     */
    @Test
    public void doPostTestFour() {
 
        // 獲得Http客戶端(可以理解為:你得先有一個(gè)瀏覽器;注意:實(shí)際上HttpClient與瀏覽器是不一樣的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
 
        // 參數(shù)
        StringBuffer params = new StringBuffer();
        try {
            // 字符數(shù)據(jù)最好encoding以下;這樣一來,某些特殊字符才能傳過去(如:某人的名字就是“&”,不encoding的話,傳不過去)
            params.append("name=" + URLEncoder.encode("&", "utf-8"));
            params.append("&");
            params.append("age=24");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
 
        // 創(chuàng)建Post請(qǐng)求
        HttpPost httpPost = new HttpPost("http://localhost:12345/doPostControllerFour" + "?" + params);
 
        // 設(shè)置ContentType(注:如果只是傳普通參數(shù)的話,ContentType不一定非要用application/json)
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
 
        // 響應(yīng)模型
        CloseableHttpResponse response = null;
        try {
            // 由客戶端執(zhí)行(發(fā)送)Post請(qǐng)求
            response = httpClient.execute(httpPost);
            // 從響應(yīng)模型中獲取響應(yīng)實(shí)體
            HttpEntity responseEntity = response.getEntity();
 
            System.out.println("響應(yīng)狀態(tài)為:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("響應(yīng)內(nèi)容長度為:" + responseEntity.getContentLength());
                System.out.println("響應(yīng)內(nèi)容為:" + EntityUtils.toString(responseEntity));
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 釋放資源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

POST有參(對(duì)象參數(shù))

/**
     * POST---有參測(cè)試(對(duì)象參數(shù))
     *
     * @date 2018年7月13日 下午4:18:50
     */
    @Test
    public void doPostTestTwo() {
 
        // 獲得Http客戶端(可以理解為:你得先有一個(gè)瀏覽器;注意:實(shí)際上HttpClient與瀏覽器是不一樣的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
 
        // 創(chuàng)建Post請(qǐng)求
        HttpPost httpPost = new HttpPost("http://localhost:12345/doPostControllerTwo");
        User user = new User();
        user.setName("潘曉婷");
        user.setAge(18);
        user.setGender("女");
        user.setMotto("姿勢(shì)要優(yōu)雅~");
        // 我這里利用阿里的fastjson,將Object轉(zhuǎn)換為json字符串;
        // (需要導(dǎo)入com.alibaba.fastjson.JSON包)
        String jsonString = JSON.toJSONString(user);
 
        StringEntity entity = new StringEntity(jsonString, "UTF-8");
 
        // post請(qǐng)求是將參數(shù)放在請(qǐng)求體里面?zhèn)鬟^去的;這里將entity放入post請(qǐng)求體中
        httpPost.setEntity(entity);
 
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
 
        // 響應(yīng)模型
        CloseableHttpResponse response = null;
        try {
            // 由客戶端執(zhí)行(發(fā)送)Post請(qǐng)求
            response = httpClient.execute(httpPost);
            // 從響應(yīng)模型中獲取響應(yīng)實(shí)體
            HttpEntity responseEntity = response.getEntity();
 
            System.out.println("響應(yīng)狀態(tài)為:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("響應(yīng)內(nèi)容長度為:" + responseEntity.getContentLength());
                System.out.println("響應(yīng)內(nèi)容為:" + EntityUtils.toString(responseEntity));
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 釋放資源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

POST有參(普通參數(shù) + 對(duì)象參數(shù))

/**
     * POST---有參測(cè)試(普通參數(shù) + 對(duì)象參數(shù))
     *
     * @date 2018年7月13日 下午4:18:50
     */
    @Test
    public void doPostTestThree() {
 
        // 獲得Http客戶端(可以理解為:你得先有一個(gè)瀏覽器;注意:實(shí)際上HttpClient與瀏覽器是不一樣的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
 
        // 創(chuàng)建Post請(qǐng)求
        // 參數(shù)
        URI uri = null;
        try {
            // 將參數(shù)放入鍵值對(duì)類NameValuePair中,再放入集合中
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("flag", "4"));
            params.add(new BasicNameValuePair("meaning", "這是什么鬼?"));
            // 設(shè)置uri信息,并將參數(shù)集合放入uri;
            // 注:這里也支持一個(gè)鍵值對(duì)一個(gè)鍵值對(duì)地往里面放setParameter(String key, String value)
            uri = new URIBuilder().setScheme("http").setHost("localhost").setPort(12345)
                    .setPath("/doPostControllerThree").setParameters(params).build();
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
        }
 
        HttpPost httpPost = new HttpPost(uri);
        // HttpPost httpPost = new
        // HttpPost("http://localhost:12345/doPostControllerThree1");
 
        // 創(chuàng)建user參數(shù)
        User user = new User();
        user.setName("潘曉婷");
        user.setAge(18);
        user.setGender("女");
        user.setMotto("姿勢(shì)要優(yōu)雅~");
 
        // 將user對(duì)象轉(zhuǎn)換為json字符串,并放入entity中
        StringEntity entity = new StringEntity(JSON.toJSONString(user), "UTF-8");
 
        // post請(qǐng)求是將參數(shù)放在請(qǐng)求體里面?zhèn)鬟^去的;這里將entity放入post請(qǐng)求體中
        httpPost.setEntity(entity);
 
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
 
        // 響應(yīng)模型
        CloseableHttpResponse response = null;
        try {
            // 由客戶端執(zhí)行(發(fā)送)Post請(qǐng)求
            response = httpClient.execute(httpPost);
            // 從響應(yīng)模型中獲取響應(yīng)實(shí)體
            HttpEntity responseEntity = response.getEntity();
 
            System.out.println("響應(yīng)狀態(tài)為:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("響應(yīng)內(nèi)容長度為:" + responseEntity.getContentLength());
                System.out.println("響應(yīng)內(nèi)容為:" + EntityUtils.toString(responseEntity));
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 釋放資源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容