马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- import cn.hutool.json.JSONUtil;
- import okhttp3.*;
- import java.io.IOException;
- import java.util.Map;
- /**
- * @ClassName OkHttpUtils
- * @description: http客户端远程调用通用工具类
- * @author: chenlf
- * @Version 1.0
- **/
- public class OkHttpUtils {
- private static OkHttpClient client = new OkHttpClient();
- public static String execute(String url, String method, RequestBody requestBody, Map<String, String> headers){
- Request.Builder requestBuilder = new Request.Builder()
- .url(url)
- .method(method, requestBody);
- if (headers != null && !headers.isEmpty()) {
- for (Map.Entry<String, String> entry : headers.entrySet()) {
- requestBuilder.addHeader(entry.getKey(), entry.getValue());
- }
- }
- try (Response response = client.newCall(requestBuilder.build()).execute()) {
- if (!response.isSuccessful())
- throw new IOException("远程调用接口失败:" + response);
- return response.body().string();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- public static String doGet(String url){
- return execute(url, "GET", null, null);
- }
- public static String doGet(String url, Map<String, String> headers){
- return execute(url, "GET", null, headers);
- }
- public static String doPost(String url, String jsonBody){
- RequestBody body = RequestBody.create(MediaType.parse("application/json"), JSONUtil.toJsonStr(jsonBody));
- return execute(url, "POST", body, null);
- }
- public static String doPost(String url, RequestBody body){
- return execute(url, "POST", body, null);
- }
- public static String doPost(String url, String jsonBody, Map<String, String> headers){
- RequestBody body = RequestBody.create(MediaType.parse("application/json"), JSONUtil.toJsonStr(jsonBody));
- return execute(url, "POST", body, headers);
- }
- public static String doPost(String url, RequestBody body, Map<String, String> headers){
- return execute(url, "POST", body, headers);
- }
- }
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |