1、httpClient的使用
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.5</version> </dependency>
// 第一步:創建一個httpClient對象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 第二步:創建一個HttpPost對象。需要指定一個url // HttpPost post = new HttpPost("http://47.244.48.xxx/xxx/xxx/"); HttpPost post = new HttpPost("http://127.0.0.1:8080/xxx/xxx/"); // 攜帶cookie String sessionId = "PHPSESSID=KSoxfJlB20JJ0..."; BasicHeader header = new BasicHeader("Cookie", sessionId); post.setHeader(header); // 第三步:創建一個list模擬表單,list中每個元素是一個NameValuePair對象 List<NameValuePair> formList = new ArrayList<>(); formList.add(new BasicNameValuePair("xxx", "xxx")); formList.add(new BasicNameValuePair("xxx", "xxx")); // 第四步:需要把表單數據包裝到Entity對象中: StringEntity StringEntity entity = new UrlEncodedFormEntity(formList, "utf-8"); post.setEntity(entity); // 第五步:執行請求。 CloseableHttpResponse response = httpClient.execute(post); // 第六步:接收返回結果 HttpEntity httpEntity = response.getEntity(); String result = EntityUtils.toString(httpEntity); System.out.println(result); // 第七步:關閉流。 response.close(); httpClient.close();
2、RestTemplate的使用:get請求帶Cookie
String url = Config.XXX_BASE_URL + "/userlevel?inviterId=" + invit1; String restInfo = MessageFormat.format("url:{0}, inviterId:{1}", url, invit1); UtilFunctions.log.info("UserController#register call rest api info, " + restInfo); HttpHeaders requestHeaders = new HttpHeaders(); List<String> cookieList = UtilFunctions.getCookieList(request); requestHeaders.put("Cookie", cookieList); HttpEntity<String> requestEntity = new HttpEntity<String>(null, requestHeaders); restTemplate.exchange(url, HttpMethod.GET, requestEntity, JSONObject.class).getBody();
UtilFunctions類的getCookieList()方法
public static List<String> getCookieList(HttpServletRequest request) { List<String> cookieList = new ArrayList<>(); Cookie[] cookies = request.getCookies(); if (cookies == null || cookies.length == 0) { return cookieList; } for (Cookie cookie : cookies) { cookieList.add(cookie.getName() + "=" + cookie.getValue()); } return cookieList; }
參考資料:
1)Springboot — 用更優雅的方式發HTTP請求(RestTemplate詳解)