okHttp3的util类

2021-04-22 01:28

阅读:553

标签:div   type   color   nts   unit   util   throws   nec   adt   

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 
 * @date 2019/11/5 17:46
 */
@Component
public class OkHttpUtil {

    public String sendPost(String url, Map 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 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类

标签:div   type   color   nts   unit   util   throws   nec   adt   

原文地址:https://www.cnblogs.com/yoyotl/p/12246708.html


评论


亲,登录后才可以留言!