OkhttpClient使用 - TFdream/blog GitHub Wiki

依赖

<dependency>
  <groupId>com.squareup.okhttp3</groupId>
  <artifactId>okhttp</artifactId>
  <version>3.9.0</version>
</dependency>

示例

结合Spring使用,如下:

package com.mindflow.http;

import okhttp3.OkHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.concurrent.TimeUnit;

/**
 * @author Ricky Fung
 */
public class OkHttpClientFactoryBean implements FactoryBean<OkHttpClient>, DisposableBean {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private long connectTimeout;
    private long readTimeout;
    private long writeTimeout;
    private String proxyHost;
    private Integer proxyPort;

    private OkHttpClient client;

    @Override
    public OkHttpClient getObject() throws Exception {

        logger.info("okhttp init connectTimeout:{}, readTimeout:{}, writeTimeout:{}, proxyAddr:{}, proxyPort:{}",
                connectTimeout, readTimeout, writeTimeout, proxyPort);

        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        client = new OkHttpClient.Builder()
                .connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
                .readTimeout(readTimeout, TimeUnit.MILLISECONDS)
                .writeTimeout(writeTimeout, TimeUnit.MILLISECONDS)
                .proxy(proxy)
                .build();
        return client;
    }

    @Override
    public Class<?> getObjectType() {
        return OkHttpClient.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void destroy() throws Exception {
        if(client!=null){
            client.connectionPool().evictAll();
            client.dispatcher().executorService().shutdown();
            client.cache().close();
        }
    }

    public void setConnectTimeout(long connectTimeout) {
        this.connectTimeout = connectTimeout;
    }

    public void setReadTimeout(long readTimeout) {
        this.readTimeout = readTimeout;
    }

    public void setWriteTimeout(long writeTimeout) {
        this.writeTimeout = writeTimeout;
    }

    public void setProxyPort(Integer proxyPort) {
        this.proxyPort = proxyPort;
    }

    public void setProxyHost(String proxyHost) {
        this.proxyHost = proxyHost;
    }
}

spring.xml

    <!--okhttp-->
    <bean id="okhttp" class="com.mindflow.http.OkHttpClientFactoryBean">
        <property name="connectTimeout" value="3000" />
        <property name="writeTimeout" value="3000" />
        <property name="readTimeout" value="3000" />
        <property name="proxyHost" value="192.168.1.1" />
        <property name="proxyPort" value="80" />
    </bean>
⚠️ **GitHub.com Fallback** ⚠️