httpClientUtil的put請求


httpClientUtil的put請求,含請求頭和請求體:

代碼:

 1 import org.apache.http.HttpEntity;
 2 import org.apache.http.ParseException;
 3 import org.apache.http.client.ClientProtocolException;
 4 import org.apache.http.client.methods.CloseableHttpResponse;
 5 import org.apache.http.client.methods.HttpPut;
 6 import org.apache.http.entity.StringEntity;
 7 import org.apache.http.impl.client.CloseableHttpClient;
 8 import org.apache.http.impl.client.HttpClients;
 9 import org.apache.http.util.EntityUtils;
10 import org.springframework.stereotype.Component;
11 
12 import java.io.IOException;
13 import java.util.Map;
14 
15 @Component
16 public class HttpRequestPutServiceImpl {
17     CloseableHttpClient httpClient = HttpClients.createDefault();
18 
19     public String doPutHttpRequest(String url, Map<String, String> headerMap,String requestBody) {
20         String entityStr = null;
21         CloseableHttpResponse response = null;
22         try {
23             HttpPut post = new HttpPut(url);
24             //添加頭部信息
25             for (Map.Entry<String, String> header : headerMap.entrySet()) {
26                 post.addHeader(header.getKey(), header.getValue());
27             }
28             HttpEntity entity = new StringEntity(requestBody,"Utf-8");
29             System.out.println("請求體是:"+requestBody);
30             post.setEntity(entity);
31             response = httpClient.execute(post);
32             // 獲得響應的實體對象
33             HttpEntity httpEntity = response.getEntity();
34             // 使用Apache提供的工具類進行轉換成字符串
35             entityStr = EntityUtils.toString(httpEntity, "UTF-8");
36             System.out.println("PUT請求路徑:"+post);
37             System.out.println("PUT請求結果:"+entityStr);
38         } catch (ClientProtocolException e) {
39             System.err.println("Http協議出現問題");
40             e.printStackTrace();
41         } catch (ParseException e) {
42             System.err.println("解析錯誤");
43             e.printStackTrace();
44         } catch (IOException e) {
45             System.err.println("IO異常");
46             e.printStackTrace();
47         }
48         return entityStr;
49     }
50 }

如有不足之處歡迎大家指導。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM