栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

自用OkHttp工具类

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

自用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;


@SuppressWarnings("all")
@Slf4j
public class OkHttpUtil {

    private static final ObjectMapper mapper = new ObjectMapper();

    
    private static String get(String requestPath, String jsonStr, List 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();
    }



    
    public static String post(String requestPath, String jsonStr, List 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();
    }


    
    public static String post(String requestPath, RequestBody body, List 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;


@Configuration
public class OkHttpConfig {
    
    @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];
            }
        };
    }

    
    @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;
    }

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

    
    @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();
    }

    
    @Bean
    public HostnameVerifier hostnameVerifier() {
        return (s, sslSession) -> Boolean.TRUE;
    }


    
    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;


@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;
		}
	}

	
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	
	public static Object getBean(String name) {
		return getApplicationContext().getBean(name);
	}

	
	public static  T getBean(Class clazz) {
		return getApplicationContext().getBean(clazz);
	}

	
	public static  T getBean(String name, Class clazz) {
		return getApplicationContext().getBean(name, clazz);
	}

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1028814.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号