首页 > 其他分享 >okhttp 使用

okhttp 使用

时间:2022-12-09 15:36:43浏览次数:41  
标签:return url Builder param 使用 okhttp new response

相关导包

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.nacos.common.utils.MapUtil;
import lombok.SneakyThrows;
import okhttp3.*;
import org.apache.commons.lang3.ObjectUtils;
import java.util.Map;
import java.util.Objects;

构建post 表单请求

             /**
     * 构造POST 表单请求
     * @param url url
     * @param fromParam form 表单参数
     * @param headers 自定义请求头
     * @return 响应流
     */
    @SneakyThrows
    public static Response doPostForm(String url, Map<String, Object> fromParam, Map<String, Object> headers) {
        //构造请求参数
        HttpUrl.Builder urlBuilder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();
        //构造请求体
        MultipartBody.Builder mBuilder = new MultipartBody.Builder();
        mBuilder.setType(MultipartBody.FORM);
        if (MapUtil.isNotEmpty(fromParam))
            fromParam.forEach((k, v) -> mBuilder.addFormDataPart(k, String.valueOf(v)));
        MultipartBody multipartBody = mBuilder.build();

        Request.Builder builder  = new Request.Builder();
        if (MapUtil.isNotEmpty(headers))
            headers.forEach((k, v) -> builder.addHeader(k, String.valueOf(v)));
        Request request = builder.url(urlBuilder.build().toString()).post(multipartBody).build();

        //发出同步请求
        return new OkHttpClient.Builder().build().newCall(request).execute();
    }

构建get请求

             /**
     * 构造GET 请求
     * @param url url
     * @param param 参数map
     * @param headers 自定义请求头
     * @return 响应流
     */
    @SneakyThrows
    public static Response doGet(String url, Map<String, Object> param, Map<String, Object> headers) {
        //构造请求参数
        HttpUrl.Builder urlBuilder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();
        if (MapUtil.isNotEmpty(param))
            param.forEach((k, v) -> urlBuilder.addQueryParameter(k, String.valueOf(v)));

        Request.Builder builder  = new Request.Builder();
        if (MapUtil.isNotEmpty(headers))
            headers.forEach((k, v) -> builder.addHeader(k, String.valueOf(v)));
        Request request = builder.url(urlBuilder.build().toString()).get().build();

        //发出同步请求
        return new OkHttpClient.Builder().build().newCall(request).execute();
    }

构建普通post请求

             /**
     * 构造携带accessToken POST 请求
     * @param url url
     * @param fromParam query请求参数 例:?userId=1&userName=张三
     * @param bodyParam 传参 raw格式
     * @return 响应流
     */
    @SneakyThrows
    public static Response doPost(String url, Map<String, Object> fromParam, Map<String, Object> bodyParam){
        //构造请求参数
        HttpUrl.Builder urlBuilder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();
        if (MapUtil.isNotEmpty(fromParam))
            fromParam.forEach((k, v) -> urlBuilder.addQueryParameter(k, String.valueOf(v)));

        //构造请求体
        RequestBody requestBody = RequestBody.
                create(MediaType.parse("application/json;charset=utf-8"), JSON.toJSONString(bodyParam));
        Request.Builder builder  = new Request.Builder();
        Request request = builder.url(urlBuilder.build().toString()).post(requestBody).build();
        //发出同步请求
        return new OkHttpClient.Builder().build().newCall(request).execute();
    }

处理Response转为JsonObject

             /**
     * okhttp3 响应处理,返回jsonObject
     * @param response 响应流
     * @return JSONObject
     */
    public static JSONObject getResponseObject(Response response){
        try {
            if (response != null && response.body() != null) {
                return JSON.parseObject(response.body().byteStream(), JSONObject.class, Feature.OrderedField);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * okhttp3 响应处理
     * @param response 响应流
     * @param cls class
     * @return class
     */
    public static <T> T getResponseObject(Response response, Class<T> cls){
        try {
            if (response != null && response.body() != null) {
                return JSON.parseObject(response.body().byteStream(), cls, Feature.OrderedField);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * okhttp3 响应处理
     * @param response 响应流
     * @param cls class
     * @param feature feature
     * @return class
     */
    public static <T> T getResponseObject(Response response, Class<T> cls, Feature feature){
        try {
            if (response != null && response.body() != null) {
                return JSON.parseObject(response.body().byteStream(), cls, feature);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

忽略 ssl 证书

             /**
     * 创建ssl http client
     * @return 忽略证书的https请求
     */
    public static OkHttpClient getSllHttpClient() {
        return new OkHttpClient.Builder()
                .sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), SSLSocketClient.getX509TrustManager())
                .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
                .build();
    }

import javax.net.ssl.*;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Arrays;

/**
 * 忽略SSL验证
 */
public class SSLSocketClient {

    //获取这个SSLSocketFactory
    public static SSLSocketFactory getSSLSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //获取TrustManager
    private static TrustManager[] getTrustManager() {
        return new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }

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

    //获取HostnameVerifier
    public static HostnameVerifier getHostnameVerifier() {
        return (s, sslSession) -> true;
    }

    public static X509TrustManager getX509TrustManager() {
        X509TrustManager trustManager = null;
        try {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init((KeyStore) null);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
                throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
            }
            trustManager = (X509TrustManager) trustManagers[0];
        } catch (Exception e) {
            e.printStackTrace();
        }

        return trustManager;
    }
}

 

标签:return,url,Builder,param,使用,okhttp,new,response
From: https://www.cnblogs.com/cxyfyf/p/16969025.html

相关文章

  • 使用IKExpression自定义函数
    背景通过字符串匹配业务表每一条记录的部分字段,来对记录打上标签要求规则可以配置调整规则支持复合运算、逻辑运算开始实现将规则放到数据库中维护从数据库......
  • 【python】Mac os M系上turtle库无法使用
    问题背景IDE:VSCodeimportturtleturtle.forward(20)warning:ThesystemversionofTkisdeprecatedandmayberemovedinafuturerelease.Pleasedon'tre......
  • AspNetCoreWebAPI使用Serilog通过配置appsettings记录日志
    继上一篇AspNetCore中使用Serilog记录日志-点终将连成线-博客园(cnblogs.com)中的日志记录配置都是写死在Program中的,本篇是通过配置文件进行配置日志记录的参数1、......
  • SDWebImage的block使用
    SDWebImageManager*sSDWebImageManagersharedManager];UIImage*cachedImage=[sdManagerimageWithUrl:url];//将需要缓存的图片加载进来//如果缓存中有图片......
  • OC之【typedef的使用】
    //#defineIntegerint//给基本数据类型起别名voidtypedefinttypedefIntegertypedefunsignedintUInteger;inta=10;Integerb=9;......
  • OC之【NSMutableString的使用】
    可变字符串的创建void//预先分配10个字数的存储空间NSMutableString*str=[[NSMutableStringalloc]initWithCapacity:10];//设置字符串内容setString:@......
  • OC之【NSArray使用】
    #import<Foundation/Foundation.h>#import"Student.h"创建一个数组void//创建一个空的数组NSArray*array=[NSArrayarray];//创建有1个元素的数组NSAr......
  • OC之【NSMutableArray的使用】
    #import<Foundation/Foundation.h>#import"Student.h"voidNSMutableArray*array=[NSMutableArrayarrayWithObject:@"1"];//添加元素addObject:@"2"];addObj......
  • OC之【NSNumber的使用】
    #import<Foundation/Foundation.h>void//将int类型的10包装成一个NSNumber对象NSNumber*number=[NSNumbernumberWithInt:10];NSLog(@"number=%@",number);......
  • OC之【NSMutableDictionary的使用】
    main.m文件#import<Foundation/Foundation.h>#import"Student.h"可变字典的使用void//创建一个空的字典NSMutableDictionary*dict=[NSMutableDictionarydicti......