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 ""; } }
上善若水,水利万物而不争。