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详解)