自用OkHttp工具类

OkHttp工具类


import com.ctrip.framework.apollo.ConfigService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.chang.util.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Ok http 请求封装
 *
 * @author dcw
 * @date on 2022/6/9 15:10
 */
@SuppressWarnings("all")
@Slf4j
public class OkHttpUtil {

    private static final ObjectMapper mapper = new ObjectMapper();

    /**
     * Get请求, 可以携带token
     * @param requestPath 请求路径
     * @param jsonStr 请求数据
     * @param head 请求头信息
     * @return
     * @throws IOException
     * @throws URISyntaxException
     */
    private static String get(String requestPath, String jsonStr, List<NameValuePair> headList) throws IOException, URISyntaxException {

        URIBuilder ub = new URIBuilder(requestPath);
        Map< String, Object > map = JsonUtil.toMap(jsonStr);

        // 拼接参数
        map.forEach((k, v) -> {
            try {
                ub.addParameter(k, v instanceof String ? (String) v : mapper.writeValueAsString(v));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        });
        URL url = ub.build().toURL();

        // 构建请求
        Request.Builder get = new Request.Builder()
                .get()
                .url(url);

        headList.forEach(head -> get.addHeader(head.getName(), head.getValue()));
        Request request = get.build();

        // 获取客户端bean
        OkHttpClient client = SpringContextUtil.getBean(OkHttpClient.class);

        // 执行请求
        Response response = client.newCall(request).execute();
        return response.body().string();
    }



    /**
     * Post请求,支持自定义haed
     *
     * @param requestPath 请求路径
     * @param jsonStr json数据
     * @param headList 请求头键值对
     * @return Response in JSON format
     */
    public static String post(String requestPath, String jsonStr, List<NameValuePair> headList) throws IOException, URISyntaxException {
        RequestBody body = RequestBody.create(MediaType.parse(WhaeeAdsConstant.APPLICATION_JSON), jsonStr);
        Request.Builder post = new Request.Builder()
                .url(requestPath)
                .post(body);

        headList.forEach(head -> post.addHeader(head.getName(), head.getValue()));
        Request request = post.build();

        // 获取客户端bean
        OkHttpClient client = SpringContextUtil.getBean(OkHttpClient.class);
        Response response = client.newCall(request).execute();
        return response.body().string();
    }


    /**
     * Post请求,支持自定义haed
     *
     * @param requestPath 请求路径
     * @param body 自定义传参
     * @param headList 请求头键值对
     * @return Response in JSON format
     */
    public static String post(String requestPath, RequestBody body, List<NameValuePair> headList) throws IOException, URISyntaxException {
        Request.Builder post = new Request.Builder()
                .url(requestPath)
                .post(body);

        headList.forEach(head -> post.addHeader(head.getName(), head.getValue()));
        Request request = post.build();

        // 获取客户端bean
        OkHttpClient client = SpringContextUtil.getBean(OkHttpClient.class);
        Response response = client.newCall(request).execute();
        return response.body().string();
    }
}

OkHttp配置

import okhttp3.ConnectionPool;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.net.ssl.*;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

/**
 * OkHttpConfig 配置类
 *
 * @author dcw
 * @date on 2022/6/8 18:26
 */
@Configuration
public class OkHttpConfig {
    /**
     * 忽略证书校验
     *
     * @return 证书信任管理器
     */
    @Bean
    public X509TrustManager x509TrustManager() {
        return new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
    }

    /**
     * 信任所有 SSL 证书
     *
     * @return
     */
    @Bean
    public SSLSocketFactory sslSocketFactory() {
        try {
            TrustManager[] trustManagers = new TrustManager[]{x509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustManagers, new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 连接池配置
     *
     * @return 连接池
     */
    @Bean
    public ConnectionPool pool() {
        // 最大连接数、连接存活时间、存活时间单位(分钟)
        return new ConnectionPool(100, 5, TimeUnit.MINUTES);
    }

    /**
     * OkHttp 客户端配置
     *
     * @return OkHttp 客户端配
     */
    @Bean
    public OkHttpClient okHttpClient() {
        return new OkHttpClient.Builder()
                .sslSocketFactory(sslSocketFactory(), x509TrustManager())
                .hostnameVerifier(hostnameVerifier())
                // 是否开启缓存
                .retryOnConnectionFailure(false)
                .connectionPool(pool())
                .connectTimeout(60L, TimeUnit.SECONDS)
                .readTimeout(60L, TimeUnit.SECONDS)
                // 禁制OkHttp的重定向操作,我们自己处理重定向
                .followRedirects(true)
                .addInterceptor(new RedirectInterceptor())
                .build();
    }

    /**
     * 信任所有主机名
     *
     * @return 主机名校验
     */
    @Bean
    public HostnameVerifier hostnameVerifier() {
        return (s, sslSession) -> Boolean.TRUE;
    }


    /**
     * Okhttp 307 重定向拦截处理
     */
    public class RedirectInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            okhttp3.Request request = chain.request();
            Response response = chain.proceed(request);
            int code = response.code();
            if (code == 307) {
                //获取重定向的地址
                String location = response.headers().get("Location");
                //重新构建请求
                Request newRequest = request.newBuilder().url(location).build();
                response = chain.proceed(newRequest);
            }
            return response;
        }
    }
    
}

Spring容器工具类


import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 提供获取被spring管理的bean对象
 * 提供环境访问方法
 *
 * @author dcw
 * @date on 2022/6/8 21:26
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {
	
	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		if (SpringContextUtil.applicationContext == null) {
			SpringContextUtil.applicationContext = applicationContext;
		}
	}

	/**
	 * 获取applicationContext
	 * @return
	 */
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	/**
	 * 通过name获取 Bean.
	 * @param name
	 * @return
	 */
	public static Object getBean(String name) {
		return getApplicationContext().getBean(name);
	}

	/**
	 * 通过class获取Bean.
	 * @param clazz
	 * @return
	 * @param 
	 */
	public static <T> T getBean(Class<T> clazz) {
		return getApplicationContext().getBean(clazz);
	}

	/**
	 * 通过name,以及Clazz返回指定的Bean
	 * @param name
	 * @param clazz
	 * @return
	 * @param 
	 */
	public static <T> T getBean(String name, Class<T> clazz) {
		return getApplicationContext().getBean(name, clazz);
	}

}

你可能感兴趣的:(随笔总结,okhttp,android)