一、httpclient保存cooki session
1. 各种http客户端说明
- httpcomponents.httpclient
- ok http 3
- Spring 的 :org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
- package org.springframework.web.client.RestTemplate
<dependency>
<groupId>org.apache.httpcomponentsgroupId>
<artifactId>httpclientartifactId>
<version>4.5.14version>
dependency>
2. 创建 CookieStore
- CookieStore 里放置 BasicClientCookie
private static CookieStore createCookieStore() {
CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("CAREYE_CORE_C_ID", "35302ee4-160d-458d-9cbc-963ea55a27eb");
cookie.setDomain("localhost");
cookie.setPath("/");
cookieStore.addCookie(cookie);
return cookieStore;
}
3. response 解析出来
public static String processResponse(CloseableHttpResponse response) throws IOException {
HttpEntity entity = response.getEntity();
if (entity != null) {
try (InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
StringBuilder responseString = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
responseString.append(line);
}
return responseString.toString();
}
}
return null;
}
只解析 1024数组
private static void myPrint(CloseableHttpResponse execute) throws Exception {
byte[] bytes = new byte[1024];
int read = execute.getEntity().getContent().read(bytes);
byte[] trueByte = Arrays.copyOf(bytes, read);
System.out.println("结果为:" + new String(trueByte));
}
4. 主逻辑 创建http client post
4.1 设置COOKIE_STORE
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("http://localhost:8088/car/getListCarInfo");
HttpCoreContext httpContext = HttpCoreContext.create();
httpContext.setAttribute(HttpClientContext.COOKIE_STORE, createCookieStore());
CloseableHttpResponse response = httpClient.execute(httpPost, httpContext);
String s = processResponse(response);
System.out.println(s);
4.2 无关紧要header头
4.3 主流程2:获取cookie session 请求参数
private void main2(String[] args) throws Exception {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpCoreContext httpContext = HttpCoreContext.create();
String url = "http://localhost:8088/usr/login";
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("checkCode", "admin"));
params.add(new BasicNameValuePair("loginName", "admin"));
params.add(new BasicNameValuePair("password", "qqqq"));
httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
CloseableHttpResponse execute = httpClient.execute(httpPost, httpContext);
BasicCookieStore store = (BasicCookieStore) httpContext.getAttribute(HttpClientContext.COOKIE_STORE);
List<Cookie> cookies = store.getCookies();
Cookie cookie = cookies.get(0);
String sessionId = cookie.getValue();
String name = cookie.getName();
System.out.println(name + ":" + sessionId);
processResponse(execute);
HttpPost httpPost2 = new HttpPost("http://localhost:8088/car/getListCarInfo");
CloseableHttpResponse response = httpClient.execute(httpPost2, httpContext);
processResponse(response);
}
4.5 HttpClients.crete和HttpClientBuilder
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
public String get(String url) throws IOException {
return send(new HttpGet(url));
}
public String send(HttpUriRequest uri) throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
uri.setHeader("Cookie", "JSESSIONID=" + session);
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(HttpClientContext.COOKIE_STORE, createCookieStore());
try (CloseableHttpResponse response = httpClient.execute(uri, httpContext)) {
return processResponse(response);
}
}
}
4.6 方式2:置超时 HttpClientBuilder
private int connectionTimeout = 10000;
private int socketTimeout = 10000;
public String get(String url, Map<String, String> headers) throws IOException {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpCoreContext httpContext = HttpCoreContext.create();
httpContext.setAttribute(HttpClientContext.COOKIE_STORE, createCookieStore());
HttpGet httpGet = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(connectionTimeout)
.setSocketTimeout(socketTimeout)
.build();
httpGet.setConfig(requestConfig);
if (headers != null && !headers.isEmpty()) {
headers.forEach(httpGet::addHeader);
}
try (CloseableHttpResponse response = httpClient.execute(httpGet, httpContext)) {
return processResponse(response);
}
}
}
public String post(String url, String body, Map<String, String> headers) throws IOException {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost httpPost = new HttpPost(url);
HttpCoreContext httpContext = HttpCoreContext.create();
httpContext.setAttribute(HttpClientContext.COOKIE_STORE, createCookieStore());
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(connectionTimeout)
.setSocketTimeout(socketTimeout)
.build();
httpPost.setConfig(requestConfig);
if (headers != null && !headers.isEmpty()) {
headers.forEach(httpPost::addHeader);
}
if (body != null && !body.isEmpty()) {
StringEntity entity = new StringEntity(body, StandardCharsets.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
}
try (CloseableHttpResponse response = httpClient.execute(httpPost, httpContext)) {
return processResponse(response);
}
}
}
4.7 无用 尝试调用
public class HttpSessionHttpUtil {
private String session;
public void login(String username, String password) {
this.session = "35302ee4-160d-458d-9cbc-963ea55a27eb";
}
public static void main(String[] args) throws IOException {
HttpSessionHttpUtil httpUtil = new HttpSessionHttpUtil();
httpUtil.login("username", "password");
String result = httpUtil.post("http://localhost:8088/car/getListCarInfo");
System.out.println(result);
}
二,其他
1. spingWeb的okHttp3
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
String url = "http://localhost:8088/car/getListCarInfo";
URI uri = URI.create(url);
ClientHttpRequest request = new OkHttp3ClientHttpRequestFactory().createRequest(uri, HttpMethod.POST);
ClientHttpResponse execute = request.execute();
System.out.println(execute.getStatusCode());
byte[] bytes = new byte[1024];
int read = execute.getBody().read(bytes);
byte[] trueByte = Arrays.copyOf(bytes, read);
System.out.println(new String(trueByte));
2. okhttp3 挺好
- 发现:Cookie 类,应该是用来处理的
- OkHttpClient
@Data
@Component
public class UrlProperties {
}
package org.jeecg.common.util.http.outproject;
import okhttp3.*;
import java.io.File;
import java.io.IOException;
import java.util.Map;
public class HttpUtil {
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private final OkHttpClient client = new OkHttpClient();
public String upload(String url, File file) throws IOException {
RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody multipartBody = (new MultipartBody.Builder())
.setType(MultipartBody.FORM)
.addFormDataPart("pdf", file.getName(), fileBody)
.build();
Request request = (new Request.Builder()).url(url).post(multipartBody).build();
return getResponseBody(request);
}
public Request form(String url, Map<String, String> form) {
FormBody.Builder formBody = new FormBody.Builder();
if (form != null && !form.isEmpty())
for (Map.Entry<String, String> entry : form.entrySet())
formBody.add(entry.getKey(), entry.getValue());
FormBody formBody1 = formBody.build();
return (new Request.Builder()).url(url).post(formBody1).build();
}
public String form(String url, Map<String, String> form, Headers headers) throws IOException {
Request request = form(url, form).newBuilder().headers(headers).build();
return getResponseBody(request);
}
public String post(String url, String json) throws IOException {
RequestBody requestBody = RequestBody.create(JSON, json);
Request request = (new Request.Builder()).url(url).post(requestBody).build();
return getResponseBody(request);
}
public String get(String url) throws IOException {
Request request = (new Request.Builder()).url(url).build();
return getResponseBody(request);
}
private String getResponseBody(Request request) throws IOException {
Response response = this.client.newCall(request).execute();
ResponseBody responseBody = response.body();
if (responseBody == null)
return "";
String result = responseBody.string();
response.close();
return result;
}
public static void main(String[] args) throws Exception {
String url = "http://localhost:8088/car/getListCarInfo";
String result = new HttpUtil().get(url);
System.out.println(result);
}
}
3. jeecg工具类 RestUtil
String url = "http://localhost:8088/car/getListCarInfo";
JSONObject result = RestUtil.post(url);
package org.springframework.web.client;
31. 其他 处理域名
package com.careye.api.util.shiro.responce;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Map;
@Slf4j
public class RestUtil {
private static String domain = null;
private static String path = null;
private static String getDomain() {
if (domain == null) {
domain = SpringContextUtils.getDomain();
String port = ":-1";
if (domain.endsWith(port)) {
domain = domain.substring(0, domain.length() - 3);
}
}
return domain;
}
private static String getPath() {
if (path == null) {
path = SpringContextUtils.getApplicationContext().getEnvironment().getProperty("server.servlet.context-path");
}
return oConvertUtils.getString(path);
}
public static String getBaseUrl() {
String basepath = getDomain() + getPath();
log.info(" RestUtil.getBaseUrl: " + basepath);
return basepath;
}
3.2 基本超时配置
private final static RestTemplate RT;
static {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(3000);
requestFactory.setReadTimeout(3000);
RT = new RestTemplate(requestFactory);
RT.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
}
public static RestTemplate getRestTemplate() {
return RT;
}
3.3 get请求 3种情况
public static JSONObject get(String url) {
return getNative(url, null, null).getBody();
}
public static JSONObject get(String url, JSONObject variables) {
return getNative(url, variables, null).getBody();
}
public static JSONObject get(String url, JSONObject variables, JSONObject params) {
return getNative(url, variables, params).getBody();
}
public static ResponseEntity<JSONObject> getNative(String url, JSONObject variables, JSONObject params) {
return request(url, HttpMethod.GET, variables, params);
}
3.4 post请求 3种情况
public static JSONObject post(String url) {
return postNative(url, null, null).getBody();
}
public static JSONObject post(String url, JSONObject params) {
return postNative(url, null, params).getBody();
}
public static JSONObject post(String url, JSONObject variables, JSONObject params) {
return postNative(url, variables, params).getBody();
}
public static ResponseEntity<JSONObject> postNative(String url, JSONObject variables, JSONObject params) {
return request(url, HttpMethod.POST, variables, params);
}
3.5 put请求 3种情况
public static JSONObject put(String url) {
return putNative(url, null, null).getBody();
}
public static JSONObject put(String url, JSONObject params) {
return putNative(url, null, params).getBody();
}
public static JSONObject put(String url, JSONObject variables, JSONObject params) {
return putNative(url, variables, params).getBody();
}
public static ResponseEntity<JSONObject> putNative(String url, JSONObject variables, JSONObject params) {
return request(url, HttpMethod.PUT, variables, params);
}
3.6 delete请求 1种情况
public static JSONObject delete(String url) {
return deleteNative(url, null, null).getBody();
}
public static JSONObject delete(String url, JSONObject variables, JSONObject params) {
return deleteNative(url, variables, params).getBody();
}
public static ResponseEntity<JSONObject> deleteNative(String url, JSONObject variables, JSONObject params) {
return request(url, HttpMethod.DELETE, null, variables, params, JSONObject.class);
}
3.7 request 组装请求
public static ResponseEntity<JSONObject> request(String url, HttpMethod method, JSONObject variables, JSONObject params) {
return request(url, method, getHeaderApplicationJson(), variables, params, JSONObject.class);
}
public static <T> ResponseEntity<T> request(String url, HttpMethod method, HttpHeaders headers, JSONObject variables, Object params, Class<T> responseType) {
log.info(" RestUtil --- request --- url = " + url);
if (StringUtils.isEmpty(url)) {
throw new RuntimeException("url 不能为空");
}
if (method == null) {
throw new RuntimeException("method 不能为空");
}
if (headers == null) {
headers = new HttpHeaders();
}
String body = "";
if (params != null) {
if (params instanceof JSONObject) {
body = ((JSONObject) params).toJSONString();
} else {
body = params.toString();
}
}
if (variables != null && !variables.isEmpty()) {
url += ("?" + asUrlVariables(variables));
}
HttpEntity<String> request = new HttpEntity<>(body, headers);
return RT.exchange(url, method, request, responseType);
}
3.8 处理Headers
public static HttpHeaders getHeaderApplicationJson() {
return getHeader(MediaType.APPLICATION_JSON_UTF8_VALUE);
}
public static HttpHeaders getHeader(String mediaType) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType(mediaType));
headers.add("Accept", mediaType);
return headers;
}
3.9 把参数组成url传输
public static String asUrlVariables(JSONObject variables) {
Map<String, Object> source = variables.getInnerMap();
Iterator<String> it = source.keySet().iterator();
StringBuilder urlVariables = new StringBuilder();
while (it.hasNext()) {
String key = it.next();
String value = "";
Object object = source.get(key);
if (object != null) {
if (!StringUtils.isEmpty(object.toString())) {
value = object.toString();
}
}
urlVariables.append("&").append(key).append("=").append(value);
}
return urlVariables.substring(1);
}
}
三,本次工具类
package org.jeecg.common.util.http;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpCoreContext;
import org.jeecg.common.exception.JeecgBootException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Component
public class HttpSessionUtil {
private String session;
private int connectionTimeout = 10000;
private int socketTimeout = 10000;
public static void main(String[] args) throws IOException {
HttpSessionUtil httpUtil = new HttpSessionUtil();
String result = httpUtil.post("http://localhost:8088/car/getListCarInfo", null, null);
System.out.println(result);
}
private void login() throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpCoreContext httpContext = HttpCoreContext.create();
String url = "http://localhost:8088/usr/login";
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("checkCode", "admin"));
params.add(new BasicNameValuePair("loginName", "admin"));
params.add(new BasicNameValuePair("password", "admin"));
httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
httpClient.execute(httpPost, httpContext);
BasicCookieStore store = (BasicCookieStore) httpContext.getAttribute(HttpClientContext.COOKIE_STORE);
List<Cookie> cookies = store.getCookies();
Cookie cookie = cookies.get(0);
String sessionId = cookie.getValue();
System.out.println("请求了Session,ID为:" + sessionId);
this.session = sessionId;
}
private RequestConfig getRequestConfig() {
return RequestConfig.custom()
.setConnectTimeout(connectionTimeout)
.setSocketTimeout(socketTimeout)
.build();
}
@NotNull
private HttpContext getHttpContext() {
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(HttpClientContext.COOKIE_STORE, createCookieStore());
return httpContext;
}
public String get(String url, Map<String, String> headers) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpContext httpContext = getHttpContext();
HttpGet httpGet = new HttpGet(url);
RequestConfig requestConfig = getRequestConfig();
httpGet.setConfig(requestConfig);
if (headers != null && !headers.isEmpty()) {
headers.forEach(httpGet::addHeader);
}
try (CloseableHttpResponse response = httpClient.execute(httpGet, httpContext)) {
String result = processResponse(response);
result = againRequest(httpClient, httpGet, result);
return result;
}
} catch (Exception e) {
e.printStackTrace();
throw new JeecgBootException("http post error" + url);
}
}
public String post(String url, String body, Map<String, String> headers) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost httpPost = new HttpPost(url);
HttpContext httpContext = getHttpContext();
RequestConfig requestConfig = getRequestConfig();
httpPost.setConfig(requestConfig);
if (headers != null && !headers.isEmpty()) {
headers.forEach(httpPost::addHeader);
}
if (body != null && !body.isEmpty()) {
StringEntity entity = new StringEntity(body, StandardCharsets.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
}
try (CloseableHttpResponse response = httpClient.execute(httpPost, httpContext)) {
String result = processResponse(response);
result = againRequest(httpClient, httpPost, result);
return result;
}
} catch (Exception e) {
e.printStackTrace();
throw new JeecgBootException("http post error" + url);
}
}
@Nullable
private String againRequest(CloseableHttpClient httpClient, HttpUriRequest httpPostOrGet, String result) throws
IOException {
System.out.println(result);
if (result.equals("{\"errCode\":2000,\"resultMsg\":\"用户未登录!\"}")) {
login();
try (CloseableHttpResponse responseAgain = httpClient.execute(httpPostOrGet, getHttpContext())) {
result = processResponse(responseAgain);
}
}
return result;
}
private CookieStore createCookieStore() {
CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("CAREYE_CORE_C_ID", session);
cookie.setDomain("localhost");
cookie.setPath("/");
cookieStore.addCookie(cookie);
return cookieStore;
}
private String processResponse(CloseableHttpResponse response) throws IOException {
HttpEntity entity = response.getEntity();
if (entity != null) {
try (InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
StringBuilder responseString = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
responseString.append(line);
}
return responseString.toString();
}
}
return null;
}
}