httpclient保存cooki session。okhttp3。RestTemplate。OkHttp3ClientHttpRequestFactory等。

一、httpclient保存cooki session

1. 各种http客户端说明

  1. httpcomponents.httpclient
  2. ok http 3
  3. Spring 的 :org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
    1. 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() {
        // 创建一个 BasicCookieStore 对象
        //chat还这样创建,报错:new InMemoryCookieStore();
        CookieStore cookieStore = new BasicCookieStore();

        // 创建一个 Cookie 对象
        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 {
        //1.获取Entity
        HttpEntity entity = response.getEntity();
        //2.不为null
        if (entity != null) {
            //3.获取内容,内容是个输入流
            try (InputStream inputStream = entity.getContent();
                 //4.创建成 缓冲流
                 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
                //5.定义 builder对象
                StringBuilder responseString = new StringBuilder();
                String line;
                //6.读取一行
                while ((line = reader.readLine()) != null) {
                    //7.添加到后面
                    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
        //1.创建 httpClient
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //2.创建HttpPost
        HttpPost httpPost = new HttpPost("http://localhost:8088/car/getListCarInfo");
        //这里不设置也行,session也能正常访问
        //httpPost.addHeader("Cookie", "JSESSIONID=589060a1-8823-4442-974a-837ef2b49e3c");

        //3.创建上下文
        HttpCoreContext httpContext = HttpCoreContext.create();
        //创建cookie
        httpContext.setAttribute(HttpClientContext.COOKIE_STORE, createCookieStore());

        //4.执行请求
        CloseableHttpResponse response = httpClient.execute(httpPost, httpContext);

        //打印
        String s = processResponse(response);

        System.out.println(s);
4.2 无关紧要header头
        // 创建 HttpGet 对象,并设置请求参数。POST也一样
        //HttpGet httpGet = new HttpGet();
        //httpGet.addHeader("Cookie", "JSESSIONID=" + sessionId);

        //Headers headers = Headers.of("abc-token", "123456");/
4.3 主流程2:获取cookie session 请求参数
    private void main2(String[] args) throws Exception {

        //创建 client 和 context 和  uri
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpCoreContext httpContext = HttpCoreContext.create();
        String url = "http://localhost:8088/usr/login";
        HttpPost httpPost = new HttpPost(url);

        //设置参数:方式1
        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));
        //设置参数:方式2
        //StringEntity entity = new StringEntity("json", StandardCharsets.UTF_8);
        //httpPost.setEntity(entity);

        //机型请求
        CloseableHttpResponse execute = httpClient.execute(httpPost, httpContext);

        // 从 HttpContext 中获取生成的 session
        //String sessionId = (String) httpContext.getAttribute(ClientContext.COOKIE_STORE);

        //获取:CookieStore
        //旧的是:ClientContext.COOKIE_STORE
        BasicCookieStore store = (BasicCookieStore) httpContext.getAttribute(HttpClientContext.COOKIE_STORE);
        //获取到 列表
        List<Cookie> cookies = store.getCookies();
        //获取单个cookies
        Cookie cookie = cookies.get(0);
        //获取到 sessionID
        String sessionId = cookie.getValue();
        //session名字
        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
        //CloseableHttpClient build = HttpClientBuilder.create().build(); 另一种

        //底层使用:HttpClientBuilder.create().build()
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
    public String get(String url) throws IOException {
        //new HttpPost(url)
        return send(new HttpGet(url));
    }
    public String send(HttpUriRequest uri) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 设置 session
            uri.setHeader("Cookie", "JSESSIONID=" + session);
            //创建上下文
            HttpContext httpContext = new BasicHttpContext();
            //设置 cookie
            httpContext.setAttribute(HttpClientContext.COOKIE_STORE, createCookieStore()); // 设置 cookie store

            //发送请求
            try (CloseableHttpResponse response = httpClient.execute(uri, httpContext)) {
                //请求处理
                return processResponse(response);
            }
        }
    }
4.6 方式2:置超时 HttpClientBuilder
    //@Component
    //@Value("${http.connection.timeout}")
    private int connectionTimeout = 10000;

    //@Value("${http.socket.timeout}")
    private int socketTimeout = 10000;

    public String get(String url, Map<String, String> headers) throws IOException {
        //1.创建
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {

            //2.创建上下文
            HttpCoreContext httpContext = HttpCoreContext.create();
            //创建cookie
            httpContext.setAttribute(HttpClientContext.COOKIE_STORE, createCookieStore());

            //3. get对象
            HttpGet httpGet = new HttpGet(url);

            //4.请求配置
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(connectionTimeout)
                    .setSocketTimeout(socketTimeout)
                    .build();
            httpGet.setConfig(requestConfig);

            //5.处理 header
            if (headers != null && !headers.isEmpty()) {
                headers.forEach(httpGet::addHeader);
            }
            //6.发送请求
            try (CloseableHttpResponse response = httpClient.execute(httpGet, httpContext)) {
                //7.处理返回
                return processResponse(response);
            }
        }
    }

    public String post(String url, String body, Map<String, String> headers) throws IOException {
        //客户端 和 URI
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost httpPost = new HttpPost(url);

            //创建上下文
            HttpCoreContext httpContext = HttpCoreContext.create();
            //创建cookie
            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);
            }

            //处理body
            if (body != null && !body.isEmpty()) {
                //创建 entity对象
                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; // 保存登录后获取的 session

    // 假设登录接口返回的响应中包含了 session 信息,这里简化处理
    public void login(String username, String password) {
        // 模拟登录操作,获取 session
        this.session = "35302ee4-160d-458d-9cbc-963ea55a27eb";
    }

    public static void main(String[] args) throws IOException {

        HttpSessionHttpUtil httpUtil = new HttpSessionHttpUtil();
        //session要赋值
        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";

		//创URL
        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 {

    /*@Value("${weatherconfig.gdUrl}")
    private String gdUrl;*/
}
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();

       /*Request request = new Request.Builder()
                .url("https://api.github.com/user")
                .header("User-Agent", "OkHttp Headers.java")
                .build();
        Response response = client.newCall(request).execute();*/

    //上传
    public String upload(String url, File file) throws IOException {
        //设备 头信息为 data
        RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        //创建 MultipartBody,类型为 form,name名为 pdf
        MultipartBody multipartBody = (new MultipartBody.Builder())
                .setType(MultipartBody.FORM)
                .addFormDataPart("pdf", file.getName(), fileBody)
                .build();
        //发送post请求
        Request request = (new Request.Builder()).url(url).post(multipartBody).build();
        return getResponseBody(request);
    }

    public Request form(String url, Map<String, String> form) {
        //构建form请求
        FormBody.Builder formBody = new FormBody.Builder();

        //循环 map,添加到 form请求里
        if (form != null && !form.isEmpty())
            for (Map.Entry<String, String> entry : form.entrySet())
                formBody.add(entry.getKey(), entry.getValue());

        //form再次构建,成 外部类
        FormBody formBody1 = formBody.build();
        //构建请求,使用 post
        return (new Request.Builder()).url(url).post(formBody1).build();
    }

    //创建form请求
    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 {
        //创建json对象
        RequestBody requestBody = RequestBody.create(JSON, json);
        //创建post请求
        Request request = (new Request.Builder()).url(url).post(requestBody).build();
        return getResponseBody(request);
    }

    public String get(String url) throws IOException {
        //创建get请求,不带参数。url就是get请求
        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();
        //如果未null,就返回空
        if (responseBody == null)
            return "";
        //返回的String
        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";
        //Headers headers = Headers.of("abc-token", "123456");

        //在工具类的第237行,添加header代码 即可
        JSONObject result = RestUtil.post(url);

		//底层使用:
		package org.springframework.web.client;
		//RestTemplate
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;

/**
 * 调用 Restful 接口 Util
 *
 * @author sunjianlei
 */
@Slf4j
public class RestUtil {

    private static String domain = null;
    private static String path = null;

    private static String getDomain() {
        if (domain == null) {
            domain = SpringContextUtils.getDomain();
            // issues/2959
            // 微服务版集成企业微信单点登录
            // 因为微服务版没有端口号,导致 SpringContextUtils.getDomain() 方法获取的域名的端口号变成了:-1所以出问题了,只需要把这个-1给去掉就可以了。
            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 基本超时配置
    /**
     * RestAPI 调用器
     */
    private final static RestTemplate RT;

    static {
        //连接 和 读取超时都是 3秒
        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种情况
 /**
     * 1.发送 get 请求。无参数
     */
    public static JSONObject get(String url) {
        return getNative(url, null, null).getBody();
    }

    /**
     * 2.发送 get 请求。有变量
     */
    public static JSONObject get(String url, JSONObject variables) {
        return getNative(url, variables, null).getBody();
    }

    /**
     * 3.发送 get 请求。有变量,有参数。解释:variables会转成这样的:a=1&b=2&c=3。params放在body里,(JSONObject) params 或 toString
     */
    public static JSONObject get(String url, JSONObject variables, JSONObject params) {
        return getNative(url, variables, params).getBody();
    }

    /**
     * 发送 get 请求,返回原生 ResponseEntity 对象
     */
    public static ResponseEntity<JSONObject> getNative(String url, JSONObject variables, JSONObject params) {
        return request(url, HttpMethod.GET, variables, params);
    }
3.4 post请求 3种情况
/**
     * 4.发送 Post 请求。无变量
     */
    public static JSONObject post(String url) {
        return postNative(url, null, null).getBody();
    }

    /**
     * 5. 发送 Post 请求。有参数
     */
    public static JSONObject post(String url, JSONObject params) {
        return postNative(url, null, params).getBody();
    }

    /**
     * 6. 发送 Post 请求。有变量,有参数
     */
    public static JSONObject post(String url, JSONObject variables, JSONObject params) {
        //ResponseEntity的泛型对应
        return postNative(url, variables, params).getBody();
    }

    /**
     * 发送 POST 请求,返回原生 ResponseEntity 对象
     */
    public static ResponseEntity<JSONObject> postNative(String url, JSONObject variables, JSONObject params) {
        return request(url, HttpMethod.POST, variables, params);
    }
3.5 put请求 3种情况
	/**
     * 7.发送 put 请求。不带参数
     */
    public static JSONObject put(String url) {
        return putNative(url, null, null).getBody();
    }

    /**
     * 8.发送 put 请求。带参数
     */
    public static JSONObject put(String url, JSONObject params) {
        return putNative(url, null, params).getBody();
    }

    /**
     * 9.发送 put 请求。带url参数 和 参数
     */
    public static JSONObject put(String url, JSONObject variables, JSONObject params) {
        return putNative(url, variables, params).getBody();
    }

    /**
     * 发送 put 请求,返回原生 ResponseEntity 对象
     */
    public static ResponseEntity<JSONObject> putNative(String url, JSONObject variables, JSONObject params) {
        return request(url, HttpMethod.PUT, variables, params);
    }
3.6 delete请求 1种情况
 	/**
     * 10.发送 delete 请求。不带参数
     */
    public static JSONObject delete(String url) {
        return deleteNative(url, null, null).getBody();
    }

    /**
     * 11.发送 delete 请求。待url参数 和 参数
     */
    public static JSONObject delete(String url, JSONObject variables, JSONObject params) {
        return deleteNative(url, variables, params).getBody();
    }

    /**
     * 发送 delete 请求,返回原生 ResponseEntity 对象
     */
    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);
    }

    /**
     * 发送请求
     *
     * @param url          请求地址
     * @param method       请求方式
     * @param headers      请求头  可空
     * @param variables    请求url参数 可空
     * @param params       请求body参数 可空
     * @param responseType 返回类型
     * @return ResponseEntity
     */
    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 = "";
        //参数不为null
        if (params != null) {
            //如果是 json
            if (params instanceof JSONObject) {
                //使用json的序列化
                body = ((JSONObject) params).toJSONString();
            } else {
                //使用String的序列化
                body = params.toString();
            }
        }
        // 拼接 url 参数
        if (variables != null && !variables.isEmpty()) {
            url += ("?" + asUrlVariables(variables));
        }
        // 发送请求:String类型的body
        HttpEntity<String> request = new HttpEntity<>(body, headers);
        return RT.exchange(url, method, request, responseType);
    }
3.8 处理Headers
	/**
     * 获取JSON请求头:json类型的header,ContentType 和 Accept
     */
    public static HttpHeaders getHeaderApplicationJson() {
        //application/json;charset=UTF-8
        return getHeader(MediaType.APPLICATION_JSON_UTF8_VALUE);
    }

    /**
     * 获取请求头
     */
    public static HttpHeaders getHeader(String mediaType) {
        //创建 header
        HttpHeaders headers = new HttpHeaders();
        //设置 ContentType ,为json
        headers.setContentType(MediaType.parseMediaType(mediaType));
        //添加头信息
        headers.add("Accept", mediaType);
        return headers;
    }
3.9 把参数组成url传输
/**
     * 将 JSONObject 转为 a=1&b=2&c=3...&n=n 的形式
     */
    public static String asUrlVariables(JSONObject variables) {
        //转成map
        Map<String, Object> source = variables.getInnerMap();
        //获取key的迭代器
        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) {
                //如果对象不为null
                if (!StringUtils.isEmpty(object.toString())) {
                    //赋值
                    value = object.toString();
                }
            }
            //拼接 &a=1
            urlVariables.append("&").append(key).append("=").append(value);
        }
        // 去掉第一个&
        return urlVariables.substring(1);
    }

}

三,本次工具类

package org.jeecg.common.util.http;

/**
 * Created on 2024/2/5.
 *
 */

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 {

    // 保存登录后获取的 session
    private String session;

    //@Value("${http.connection.timeout}")
    private int connectionTimeout = 10000;

    //@Value("${http.socket.timeout}")
    private int socketTimeout = 10000;

    //HttpClientBuilder.create().build() 一样。定义到这里交给Spring反而更慢。
    //private static final CloseableHttpClient INSTANCE = HttpClients.createDefault();
    //上下文
    //private static final BasicHttpContext CONTEXT = new BasicHttpContext();

    //测试
    public static void main(String[] args) throws IOException {

        HttpSessionUtil httpUtil = new HttpSessionUtil();
        //session要赋值
        //httpUtil.login();

        String result = httpUtil.post("http://localhost:8088/car/getListCarInfo", null, null);
        System.out.println(result);
    }

    //登录接口返回的响应中包含了 session。String username, String password
    private void login() throws IOException {
        //创建 client 和 context 和  uri
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();//INSTANCE
        HttpCoreContext httpContext = HttpCoreContext.create();
        String url = "http://localhost:8088/usr/login";
        HttpPost httpPost = new HttpPost(url);

        //设置参数:方式1
        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));
        //设置参数:方式2
        //StringEntity entity = new StringEntity("json", StandardCharsets.UTF_8);
        //httpPost.setEntity(entity);

        //进行机型请求 CloseableHttpResponse execute =
        httpClient.execute(httpPost, httpContext);

        //获取:CookieStore。旧的是:ClientContext.COOKIE_STORE
        BasicCookieStore store = (BasicCookieStore) httpContext.getAttribute(HttpClientContext.COOKIE_STORE);
        //获取到 列表
        List<Cookie> cookies = store.getCookies();
        //获取单个cookies
        Cookie cookie = cookies.get(0);
        //获取到 sessionID
        String sessionId = cookie.getValue();

        System.out.println("请求了Session,ID为:" + sessionId);

        // 模拟登录操作,获取 session
        this.session = sessionId;
    }
    //session名字
    //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);

    /**
     * 获取配置对象
     *
     * @return
     */
    private RequestConfig getRequestConfig() {
        //4.请求配置
        return RequestConfig.custom()
                .setConnectTimeout(connectionTimeout)
                .setSocketTimeout(socketTimeout)
                .build();
    }

    @NotNull
    private HttpContext getHttpContext() {
        //创建上下文
        HttpContext httpContext = new BasicHttpContext();
        //设置 cookie
        httpContext.setAttribute(HttpClientContext.COOKIE_STORE, createCookieStore()); // 设置 cookie store
        return httpContext;
    }

    public String get(String url, Map<String, String> headers) {
        //1.创建 INSTANCE
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {

            //2.创建上下文
            HttpContext httpContext = getHttpContext();

            //3. get对象
            HttpGet httpGet = new HttpGet(url);

            RequestConfig requestConfig = getRequestConfig();
            httpGet.setConfig(requestConfig);

            //5.处理 header
            if (headers != null && !headers.isEmpty()) {
                headers.forEach(httpGet::addHeader);
            }
            //6.发送请求
            try (CloseableHttpResponse response = httpClient.execute(httpGet, httpContext)) {
                //7.处理返回
                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) {
        //客户端 和 URI
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {// INSTANCE

            HttpPost httpPost = new HttpPost(url);

            //创建上下文
            HttpContext httpContext = getHttpContext();

            //配置
            RequestConfig requestConfig = getRequestConfig();
            httpPost.setConfig(requestConfig);

            //设置头
            if (headers != null && !headers.isEmpty()) {
                headers.forEach(httpPost::addHeader);
            }

            //处理body
            if (body != null && !body.isEmpty()) {
                //创建 entity对象
                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() {
        // 创建一个 BasicCookieStore 对象
        CookieStore cookieStore = new BasicCookieStore();
        // 创建一个 Cookie 对象
        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 {
        //1.获取Entity
        HttpEntity entity = response.getEntity();
        //2.不为null
        if (entity != null) {
            //3.获取内容,内容是个输入流
            try (InputStream inputStream = entity.getContent();
                 //4.创建成 缓冲流
                 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
                //5.定义 builder对象
                StringBuilder responseString = new StringBuilder();
                String line;
                //6.读取一行
                while ((line = reader.readLine()) != null) {
                    //7.添加到后面
                    responseString.append(line);
                }
                //返回
                return responseString.toString();
            }
        }
        return null;
    }

    /*public String get(String url) throws IOException {
        //new HttpPost(url)
        HttpGet httpGet = new HttpGet(url);
        RequestConfig requestConfig = getRequestConfig();
        httpGet.setConfig(requestConfig);

        //CloseableHttpClient build = HttpClientBuilder.create().build(); 另一种方式创建
        //底层使用:HttpClientBuilder.create().build()
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 设置 session
            httpGet.setHeader("Cookie", "JSESSIONID=" + session);
            HttpContext httpContext = getHttpContext();
            //发送请求
            try (CloseableHttpResponse response = httpClient.execute(httpGet, httpContext)) {
                //请求处理
                return processResponse(response);
            }
        }
    }*/
}

你可能感兴趣的:(Java,EE,okhttp,http,restTemplate)