<!--okhttp3--> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.13.1</version> </dependency>
import okhttp3.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.CollectionUtils; import java.io.IOException; import java.util.Map; import java.util.Objects; /** * 利用OKHttp进行get和post的访问 * */ public class OKHttpUtil { static final Logger logger = LoggerFactory.getLogger(OKHttpUtil.class); /** * 发起get请求 * * @param url * @return */ public static String httpGet(String url) { String result = null; OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).build(); try { Response response = client.newCall(request).execute(); result = response.body().string(); } catch (Exception e) { e.printStackTrace(); } return result; } /** * 执行同步 Post请求 * @param url * @param jsonStr * @param headers * @return * @throws IOException */ public static Response httpPost(String url, String jsonStr, Map<String, String> headers) throws IOException { //构造请求体 RequestBody requestBody = RequestBody.create(MediaType.parse("text/html;charset=utf-8"), jsonStr); //创建requestBody Request.Builder requestBuilder = new Request.Builder().url(url).post(requestBody); //构造请求头 if(!CollectionUtils.isEmpty(headers)){ for (Map.Entry<String, String> mapEntry : headers.entrySet()) { // value不为空 if(!Objects.isNull(mapEntry.getValue())){ requestBuilder.addHeader(mapEntry.getKey(), String.valueOf(mapEntry.getValue())); } } } //构建请求 Request request = requestBuilder.build(); //获取client OkHttpClient okHttpClient = new OkHttpClient(); //执行 Response response = okHttpClient.newCall(request).execute(); return response; } }
原文:https://www.cnblogs.com/21-Gram/p/11319524.html