欢迎光临
我们一直在努力

Okhttp GET/POST请求示例

OkHTTP使用示例。

一、环境信息

  • JDK 1.8;
  • 调用方式:OKHTTP 4.9.0;

二、工具类

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.util.Map;

public class OkHttpUtil {

    /**
     * 使用OkHttp发送get请求
     *
     * @param url 请求地址
     * @return 返回结果
     */
    public static String sendGet(String url) {
        String result = null;
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            result = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 使用OkHttp发送get请求
     *
     * @param url    请求地址
     * @param header 请求头Headers
     * @return 返回结果
     */
    public static String sendGetWithHeader(String url, Map<String, String> header) {
        String result = null;
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", header.get("Authorization"))
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            result = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 使用OkHttp发送post请求
     *
     * @param url    请求地址
     * @param params 请求参数
     * @return 返回结果
     */
    public static String sendPost(String url, Map<String, Object> params) {
        String result = null;
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = RequestBody.create(JSONObject.toJSONString(params), MediaType.get("application/json"));

        //创建一个请求对象
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        //发送请求获取响应
        try {
            Response response = okHttpClient.newCall(request).execute();
            result = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 使用OkHttp发送post请求
     *
     * @param url    请求地址
     * @param params 请求参数
     * @return 返回结果
     */
    public static String sendPostWithHeader(String url, Map<String, Object> params, Map<String, String> header) {
        String result = null;
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = RequestBody.create(JSONObject.toJSONString(params), MediaType.get("application/json"));

        //创建一个请求对象
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", header.get("Authorization"))
                .post(requestBody)
                .build();
        //发送请求获取响应
        try {
            Response response = okHttpClient.newCall(request).execute();
            result = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 解决接口地址自签名证书不受信任的情况
     * <p>
     * This is very bad practice and should NOT be used in production.
     *
     * @return OkHttpClient
     */
    private static OkHttpClient getUnsafeOkHttpClient() {
        try {
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
            builder.hostnameVerifier((hostname, session) -> true);
            OkHttpClient okHttpClient = builder.build();
            return okHttpClient;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 使用OkHttp发送get请求(绕过SSL证书验证)
     *
     * @param url 请求地址
     * @return 返回结果
     */
    public static String sendGetTrustAllCerts(String url) {
        String result = null;
        OkHttpClient okHttpClient = getUnsafeOkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            result = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 使用OkHttp发送post请求(绕过SSL证书验证)
     *
     * @param url    请求地址
     * @param params 请求参数
     * @return 返回结果
     */
    public static String sendPostTrustAllCerts(String url, Map<String, Object> params) {
        String result = null;
        OkHttpClient okHttpClient = getUnsafeOkHttpClient();
        RequestBody requestBody = RequestBody.create(JSONObject.toJSONString(params), MediaType.get("application/json"));

        //创建一个请求对象
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        //发送请求获取响应
        try {
            Response response = okHttpClient.newCall(request).execute();
            result = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 使用OkHttp发送post请求(绕过SSL证书验证)
     *
     * @param url    请求地址
     * @param params 请求参数
     * @return 返回结果
     */
    public static String sendPostWithHeaderTrustAllCerts(String url, Map<String, Object> params, Map<String, String> header) {
        String result = null;
        OkHttpClient okHttpClient = getUnsafeOkHttpClient();
        RequestBody requestBody = RequestBody.create(JSONObject.toJSONString(params), MediaType.get("application/json"));

        //创建一个请求对象
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", header.get("Authorization"))
                .post(requestBody)
                .build();
        //发送请求获取响应
        try {
            Response response = okHttpClient.newCall(request).execute();
            result = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

}
赞(0)
未经允许不得转载:Ddmit » Okhttp GET/POST请求示例

评论 抢沙发

登录

找回密码

注册