來自:HttpClient實現 get、post、put、delete請求_httpclient put請求-CSDN博客
目錄
HttpClient
HttpClient的主要功能
httpclient使用示例主要步驟
Spring Boot 工程結構
HttpClient實現主要代碼:
GET
POST
PUT
Delete?
HttpClient
HttpClient 是Apache Jakarta Common 下的子項目,可以用來提供高效的、最新的、功能豐富的支持 HTTP 協議的客戶端編程工具包,方便在日常項目開發中,調用第三方接口數據。
HttpClient的主要功能
實現了所有 HTTP 的方法(GET、POST、PUT、HEAD、DELETE、HEAD、OPTIONS 等)
支持 HTTPS 協議
支持代理服務器(Nginx等)等
支持自動(跳轉)轉向
環境說明:JDK1.8、SpringBoot(2.2.2)
在pom.xml中引入HttpClient的依賴和SpringBoot的基本依賴配置(web,jpa,fastjson,mysql)。
<dependency>
? ? <groupId>org.apache.httpcomponents</groupId>
? ? <artifactId>httpclient</artifactId>
? ? <version>4.5.3</version>
</dependency>
httpclient使用示例主要步驟
【步驟】:
1)創建一個httpclient對象,注意以下版本問題說明
HttpClient4.0版本前:
HttpClient httpClient = new DefaultHttpClient();
4.0版本后:
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
2)創建一個httpGet對象
HttpGet request = new HttpGet(uri);
3)執行請求調用httpclient的execute(),傳入httpGet對象,返回CloseableHttpResponse response = httpClient.execute(request, HttpClientContext.create());
4)取得響應結果并處理
5)關閉HttpClient
注意:主動設置編碼,防止響應出現亂碼
Spring Boot 工程結構
HttpClient實現主要代碼:
GET
? /**GET有參:
? ? ?*/
? ? @Autowired
? ? private UserServiceImple userServiceImple;
? ? @Test
? ? public void getByUsername(){
? ? ? ? List<User> users = userServiceImple.findByUserName("王三");
? ? ? ? System.out.println(JSON.toJSONString(users));
?
? ? }
? ? @Test
? ? public void doGetTestWayOne() {
? ? ? ? // 獲得Http客戶端(可以理解為:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)
? ? ? ? CloseableHttpClient httpClient = HttpClientBuilder.create().build();
?
? ? ? ? // 創建Get請求
? ? ? ? HttpGet httpGet = new HttpGet("http://localhost:8080/user/2");
? ? ? ? // 響應模型
? ? ? ? CloseableHttpResponse response = null;
? ? ? ? try {
? ? ? ? ? ? // 配置信息
? ? ? ? ? ? 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, StandardCharsets.UTF_8));
? ? ? ? ? ? }
? ? ? ? } 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---有參測試(對象參數)
? ? ?*
? ? ?* @date
? ? ?*/
? ? @Test
? ? public void dopostHaveObjectParam() {
?
? ? ? ? // 獲得Http客戶端(可以理解為:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)
? ? ? ? CloseableHttpClient httpClient = HttpClientBuilder.create().build();
?
? ? ? ? // 創建Post請求
? ? ? ? HttpPost httpPost = new HttpPost("http://localhost:8080/user");
? ? ? ? User user = new User();
? ? ? ? user.setUserName("張山");
? ? ? ? user.setPassword("Ss@1234");
? ? ? ? // 我這里利用阿里的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 = null;
? ? ? ? try {
? ? ? ? ? ? // 由客戶端執行(發送)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, StandardCharsets.UTF_8));
? ? ? ? ? ? }
? ? ? ? } 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();
? ? ? ? ? ? }
? ? ? ? }
? ? }
PUT
? /**
? ? ?* Put---有參測試(對象參數)
? ? ?*
? ? ?* @date
? ? ?*/
? ? @Test
? ? public void doPutObjectParam() {
?
? ? ? ? // 獲得Http客戶端(可以理解為:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)
? ? ? ? CloseableHttpClient httpClient = HttpClientBuilder.create().build();
?
? ? ? ? // 創建Put請求
? ? ? ? HttpPost httpPut = new HttpPost("http://localhost:8080/user");
? ? ? ? User user = new User();
? ? ? ? user.setId((long) 2);
? ? ? ? user.setUserName("張山");
? ? ? ? user.setPassword("Ss@1234");
? ? ? ? // 我這里利用阿里的fastjson,將Object轉換為json字符串;
? ? ? ? // (需要導入com.alibaba.fastjson.JSON包)
? ? ? ? String jsonString = JSON.toJSONString(user);
? ? ? ? // ?主動設置編碼,防止出現亂碼
? ? ? ? StringEntity entity = new StringEntity(jsonString, "UTF-8");
?
? ? ? ? // post請求是將參數放在請求體里面傳過去的;這里將entity放入Put請求體中
? ? ? ? httpPut.setEntity(entity);
?
? ? ? ? httpPut.setHeader("Content-Type", "application/json;charset=utf8");
?
? ? ? ? // 響應模型
? ? ? ? CloseableHttpResponse response = null;
? ? ? ? try {
? ? ? ? ? ? // 由客戶端執行(發送)Put請求
? ? ? ? ? ? response = httpClient.execute(httpPut);
? ? ? ? ? ? // 從響應模型中獲取響應實體
? ? ? ? ? ? HttpEntity responseEntity = response.getEntity();
?
? ? ? ? ? ? System.out.println("響應狀態為:" + response.getStatusLine());
? ? ? ? ? ? if (responseEntity != null) {
? ? ? ? ? ? ? ? System.out.println("響應內容長度為:" + responseEntity.getContentLength());
? ? ? ? ? ? ? ? //主動設置編碼,防止相應出現亂碼
? ? ? ? ? ? ? ? System.out.println("響應內容為:" + EntityUtils.toString(responseEntity, StandardCharsets.UTF_8));
? ? ? ? ? ? }
? ? ? ? } 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();
? ? ? ? ? ? }
? ? ? ? }
? ? }
Delete?
? /**
? ? ?* DeleteTest
? ? ?*/
?
? ? @Test
? ? public void doDeleteTest() {
? ? ? ? // 獲得Http客戶端(可以理解為:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)
? ? ? ? CloseableHttpClient httpClient = HttpClientBuilder.create().build();
? ? ? ? // 創建Delete請求
? ? ? ? HttpDelete httpDelete = new HttpDelete("http://localhost:8080/user/41");
? ? ? ? // 響應模型
? ? ? ? CloseableHttpResponse response = null;
? ? ? ? try {
? ? ? ? ? ? // 配置信息
? ? ? ? ? ? RequestConfig requestConfig = RequestConfig.custom()
? ? ? ? ? ? ? ? ? ? // 設置連接超時時間(單位毫秒)
? ? ? ? ? ? ? ? ? ? .setConnectTimeout(5000)
? ? ? ? ? ? ? ? ? ? // 設置請求超時時間(單位毫秒)
? ? ? ? ? ? ? ? ? ? .setConnectionRequestTimeout(5000)
? ? ? ? ? ? ? ? ? ? // socket讀寫超時時間(單位毫秒)
? ? ? ? ? ? ? ? ? ? .setSocketTimeout(5000)
? ? ? ? ? ? ? ? ? ? // 設置是否允許重定向(默認為true)
? ? ? ? ? ? ? ? ? ? .setRedirectsEnabled(true).build();
?
? ? ? ? ? ? // 將上面的配置信息 運用到這個Delete請求里
? ? ? ? ? ? httpDelete.setConfig(requestConfig);
?
? ? ? ? ? ? // 由客戶端執行(發送)Delete請求
? ? ? ? ? ? response = httpClient.execute(httpDelete);
?
? ? ? ? ? ? // 從響應模型中獲取響應實體
? ? ? ? ? ? HttpEntity responseEntity = response.getEntity();
? ? ? ? ? ? System.out.println("響應狀態為:" + response.getStatusLine());
? ? ? ? ? ? if (responseEntity != null) {
? ? ? ? ? ? ? ? System.out.println("響應內容長度為:" + responseEntity.getContentLength());
? ? ? ? ? ? ? ? //主動設置編碼,防止相應出現亂碼
? ? ? ? ? ? ? ? System.out.println("響應內容為:" + EntityUtils.toString(responseEntity, StandardCharsets.UTF_8));
? ? ? ? ? ? }
? ? ? ? } 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();
? ? ? ? ? ? }
? ? ? ? }
? ? }
————————————————
版權聲明:本文為CSDN博主「紫金小飛俠」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/yangshengwei230612/article/details/103964905