okhttp3使用总结

该博客介绍了如何利用Postman测试HTTP接口并生成代码,特别是针对文件上传的问题。作者通过Postman生成了依赖于OkHttp3的工具类,设置了超时时间并处理了HTTPS的证书验证。此外,还提供了包括文件上传、POST JSON数据、GET请求等在内的多种HTTP方法的实现,并展示了如何处理编码问题和进行文件下载。这个工具类简化了Java中进行HTTP请求的流程。
摘要由CSDN通过智能技术生成

一次分析接口对接,需要上传文件,使用httpclient始终报错,使用postman调试,测通了。于是想到了postman的代码生成功能,可以将测通代码拿来调整一下使用。

其他的各种参数类型都可以先用postman测通,然后参考生成的代码,减少工作量

 

生成的代码依赖是http3,由此封装出okhttp3的工具类,方便后续使用。

maven依赖

       <!-- okhttp3-->  
       <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.3.0</version>
       </dependency>

        <!-- commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>


        <!--GetByteEncode-->
        <dependency>
            <groupId>com.googlecode.juniversalchardet</groupId>
            <artifactId>juniversalchardet</artifactId>
            <version>1.0.3</version>
        </dependency>

        <!--GetByteEncode-->
        <dependency>
            <groupId>com.googlecode.juniversalchardet</groupId>
            <artifactId>juniversalchardet</artifactId>
            <version>1.0.3</version>
        </dependency>

        <!-- commons-lang -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.7</version>
        </dependency>

 

package com.wg.utils;

import okhttp3.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.RequestBuilder;
import org.elasticsearch.client.Requests;
import org.mozilla.universalchardet.UniversalDetector;

import javax.net.ssl.*;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class OkHttpUtil {

    //单例构造
    static class Singlton{
        public  static  OkHttpClient client = new okhttp3.OkHttpClient.Builder()
                .readTimeout(20, TimeUnit.SECONDS)//读取超时
                .connectTimeout(60, TimeUnit.SECONDS)//连接超时
                .writeTimeout(60, TimeUnit.SECONDS)//写入超时
                支持HTTPS请求,跳过证书验证
                .sslSocketFactory(createSSLSocketFactory())
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                })
                .build();
    }

    private static Map<String, String> defaultHeader = new HashMap<>();
    static {
        defaultHeader.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
//        defaultHeader.put("Accept-Encoding", "gzip, deflate"); //okhttp不支持这个参数的解压缩
        defaultHeader.put("accept-language", "zh-CN,zh;q=0.9,en;q=0.8");
        defaultHeader.put("cache-control", "max-age=0");
        defaultHeader.put("upgrade-insecure-requests", "1");
        defaultHeader.put("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
        defaultHeader.put("referer", "https://www.baidu.com");
    }


    /**
     * 文件上传
     * @param file
     * @param url
     * @param name
     * @return
     */
    public static String upload(File file,String url,String name){
        OkHttpClient client = new OkHttpClient().newBuilder()
                .connectTimeout(60*5, TimeUnit.SECONDS)
                .readTimeout(60*5, TimeUnit.SECONDS)
                .build();

        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart(name,file.getName(),
                        RequestBody.create(MediaType.parse("application/octet-stream"),
                                file))
                .build();
        Request request = new Request.Builder()
                .url(url)
                .method("POST", body)
                .build();
       return  execute(request);
    }

    private static final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");
    /**
     * 生成安全套接字工厂,用于https请求的证书跳过
     * @return
     */
    public static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssfFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());
            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
        }
        return ssfFactory;
    }
    /**
     * 用于信任所有证书
     */
    static class TrustAllCerts implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        }
        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

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



   public static String postJson(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = Singlton.client.newCall(request).execute();
        return response.body().string();
    }
   public static String postJson(String url, String json,Map<String,String> headerMap) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .headers(getHeaders(headerMap))
                .post(body)
                .build();
        Response response = Singlton.client.newCall(request).execute();
        return response.body().string();
    }


    public static String postForm(String url, Map<String,String> forms) throws IOException {
        FormBody.Builder formBuilder = new FormBody.Builder();
        for (Map.Entry<String, String> entry : forms.entrySet()) {
            formBuilder.add(entry.getKey(),entry.getValue());
//使用 addEncoded() 方法,添加已经被编码(utf-8)的参数的值 ,okhttp将不再对此参数的值进行默认编码
//            formBuilder.addEncoded(entry.getKey(),encode(entry.getValue()));
        }

        FormBody body =formBuilder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        return  execute(request);
    }


    private static String encode(String str){
        try {
            return  URLEncoder.encode(str,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String execute(Request request){
        Response response=null;
        try {
             response = Singlton.client.newCall(request).execute();
            if (response.isSuccessful()) {
                byte[] bytes = response.body().bytes();
                String encoding = getEncoding(bytes);
                return new String(bytes, encoding);
            }else {
                System.out.println(response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(response!=null){
                response.close();
            }
        }
        return null;
    }

    public static String execute(Request request,String charset){
        Response response=null;
        try {
             response = Singlton.client.newCall(request).execute();
            if (response.isSuccessful()) {
                return new String(response.body().bytes(), charset);
            }else {
                System.out.println(response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(response!=null){
                response.close();
            }
        }
        return null;
    }

    /**
     * curl -XDELETE
     * @param url
     * @param reqbody
     * @param map
     * @return
     */
    public static String doDelete(String url,String reqbody,Map<String,Object> map){
        FormBody.Builder builder=addParamToBuilder(reqbody, map);
        RequestBody body = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .delete(body)
                .build();
        return execute(request);
    }

    public static String doGet(String url,Map<String,String> headerMap,String charset){
        Headers mHeaders=getHeaders(headerMap);

        Request request = new Request.Builder()
                .get()
                .url(url)
                .headers(mHeaders)
                .build();
        return execute(request,charset);
    }

    /**
     * 封装header
     * @param headerMap
     * @return
     */
    public static Headers getHeaders(Map<String,String> headerMap){
        Headers mHeaders=null;
        if(headerMap==null){
            mHeaders = Headers.of(defaultHeader);
        }else {
            mHeaders = Headers.of(headerMap);
        }
        return mHeaders;
    }

    /**
     * curl -XPOST
     * @param url
     * @param reqbody
     * @param map
     * @return
     */
    public static String doPost(String url,String reqbody,Map<String,Object> map){
        FormBody.Builder  builder=addParamToBuilder(reqbody, map);
        RequestBody body = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        return execute(request);
    }

    public static final MediaType MEDIA_TYPE_MARKDOWN
            = MediaType.parse("text/x-markdown; charset=utf-8");

    /**
     *  curl -XPOST 请求体带json
     * @param url
     * @param reqbody
     * @return
     */
    public static String doPost(String url,String reqbody){
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, reqbody))
                .build();
        return execute(request);
    }

    public static FormBody.Builder  addParamToBuilder(String reqbody,Map<String,Object> map){
        FormBody.Builder builder = new FormBody.Builder();
        if(!StringUtils.isEmpty(reqbody)){
            if(reqbody.startsWith("?")){
                reqbody=reqbody.substring(1);
            }
            String[] params=reqbody.split("&");
            for(int i=0;i<params.length;i++){
                if(params[i].equals("")){
                    continue;
                }
                String [] kv=params[i].split("=");
                builder.add(kv[0], kv[1]);
            }
        }



        if(map!=null){
            Iterator<Map.Entry<String,Object>> ite= map.entrySet().iterator();
            for(;ite.hasNext();){
                Map.Entry<String,Object> kv=ite.next();
                builder.add(kv.getKey(), kv.getValue().toString());
            }
        }
        return builder;
    }

    public static void downFile(String url,String dataDir,String fileName,boolean deleteOld){
        File dataFile =new File( new File(dataDir)+File.separator+fileName);
        if(!dataFile.getParentFile().exists()){
            dataFile.mkdirs();
        }else {
            if(deleteOld){
                dataFile.delete();
            }
        }

        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();
        Response response=null;
        try {
            response = Singlton.client.newCall(request).execute();
            FileUtils.copyInputStreamToFile(response.body().byteStream(),dataFile);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(response!=null){
                response.close();
            }
        }
    }

    /**
     * 获取编码
     * @param bytes
     * @return
     */
    public static String getEncoding(byte[] bytes) {
        String defaultEncoding = "UTF-8";
        UniversalDetector detector = new UniversalDetector(null);
        detector.handleData(bytes, 0, bytes.length);
        detector.dataEnd();
        String encoding = detector.getDetectedCharset();
        detector.reset();
        System.out.println("字符编码是:"+ encoding);
        if (encoding == null) {
            encoding = defaultEncoding;
        }
        return encoding;


    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值