美文网首页
okhttp框架实现http的调用

okhttp框架实现http的调用

作者: 天草二十六_简村人 | 来源:发表于2022-12-17 00:08 被阅读0次

    一、pom.xml

            <!-- OKHttp -->
            <dependency>
                <groupId>com.squareup.okhttp3</groupId>
                <artifactId>okhttp</artifactId>
                <version>3.14.9</version>
            </dependency>
    

    二、源码实现

    import tech.powerjob.common.exception.PowerJobException;
    import okhttp3.*;
    
    import java.io.IOException;
    import java.util.concurrent.TimeUnit;
    
    /**
     * 封装 OkHttpClient
     *
     * @author tjq
     * @since 2020/4/6
     */
    public class HttpUtils {
    
        private static final OkHttpClient client;
        private static final int HTTP_SUCCESS_CODE = 200;
    
        static {
            client = new OkHttpClient.Builder()
                    .connectTimeout(1, TimeUnit.SECONDS)
                    .readTimeout(5, TimeUnit.SECONDS)
                    .build();
        }
    
        public static String get(String url) throws IOException {
            Request request = new Request.Builder()
                    .get()
                    .url(url)
                    .build();
            return execute(request);
        }
    
        public static String post(String url, RequestBody requestBody) throws IOException {
            Request request = new Request.Builder()
                    .post(requestBody)
                    .url(url)
                    .build();
            return execute(request);
        }
    
        private static String execute(Request request) throws IOException {
            try (Response response = client.newCall(request).execute()) {
                int responseCode = response.code();
                if (responseCode == HTTP_SUCCESS_CODE) {
                    ResponseBody body = response.body();
                    if (body == null) {
                        return null;
                    }else {
                        return body.string();
                    }
                }
                throw new PowerJobException(String.format("http request failed,code=%d", responseCode));
            }
        }
    
    }
    
    

    三、使用示例

    post请求

    RequestBody body = new FormBody.Builder()
                    .add("wfInstanceId", wfInstanceId.toString())
                    .add("appId", appId.toString())
                    .build();
    
    String res = HttpUtils.post(url, requestBody);
    

    get 请求

    HttpUtils.get(url)
    

    相关文章

      网友评论

          本文标题:okhttp框架实现http的调用

          本文链接:https://www.haomeiwen.com/subject/czadqdtx.html