okHttp3的util类

Posted yoyotl

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了okHttp3的util类相关的知识,希望对你有一定的参考价值。

package com.sanro.common.util;

import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author LingSong <19039339@cnsuning.com>
 * @date 2019/11/5 17:46
 */
@Component
public class OkHttpUtil {

    public String sendPost(String url, Map<String, String> map) {
        String responseBody = "";
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder().connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(120, TimeUnit.SECONDS).build();
        FormBody.Builder builder = new FormBody.Builder();
        for(Map.Entry<String,String> entry : map.entrySet()){
            builder.add(entry.getKey(),entry.getValue());
        }
        RequestBody body = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            responseBody = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseBody;
    }

    public String sendAsynPost(String reqUrl, String body) {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(reqUrl)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println("异步线程Id为:" + Thread.currentThread().getId());
            }
        });

        return "";
    }
}

 

以上是关于okHttp3的util类的主要内容,如果未能解决你的问题,请参考以下文章

无法解析方法'create(okhttp3.MediaType, java.util.List<java.lang.String>)'

Java封装OkHttp3工具类

Java封装OkHttp3工具类

js代码片段: utils/lcoalStorage/cookie

二进制 XML 文件第 13 行:膨胀类片段时出错

缺少类:okhttp3.internal.http.UnrepeatableRequestBody