实战:第二十五章:HttpUtil代理

Posted java_wxid

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了实战:第二十五章:HttpUtil代理相关的知识,希望对你有一定的参考价值。

package com.common.entity.utils;

import okhttp3.*;
import org.springframework.http.HttpStatus;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.concurrent.TimeUnit;

/**
 * @author zhiwei Liao
 * @version 1.0
 * @Date 2021/5/8 17:20
 */


public class HttpUtil {

    private static OkHttpClient client;

    private static final String DEFAULT_MEDIA_TYPE = "application/json; charset=utf-8";

    private static final int CONNECT_TIMEOUT = 15;

    private static final int READ_TIMEOUT = 17;

    private static final String GET = "GET";

    private static final String POST = "POST";

    /**
     * 单例模式  获取类实例
     *
     * @return client
     */
    private static OkHttpClient getInstance() {
        if (client == null) {
            synchronized (OkHttpClient.class) {
                if (client == null) {
                    client = new OkHttpClient.Builder()
                            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                            .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                            .build();
                }
            }
        }
        return client;
    }

    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\\"messages\\":[{\\"from\\":\\"bamboo8\\",\\"destinations\\":[{\\"to\\":\\"0086 17717299170\\"}],\\"text\\":\\"1234 is your verification code\\"}]}");
        Request request = new Request.Builder()
                .url("https://qgk983.api.infobip.com/sms/2/text/advanced")
                .method("POST", body)
                .addHeader("Authorization", "Basic cWlhbmd5dTpxdWFkdGFsZW50QEI4")
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        try {
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            String result = responseBody.string();
            System.out.println(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String doGet(String url) throws Exception{
        try {
            long startTime = System.currentTimeMillis();
            Request request = new Request.Builder().url(url).build();
            // 开启代理
            String proxyHost = "127.0.0.1";
            String proxyPort = "7890";
            System.setProperty("http.proxyHost", proxyHost);
            System.setProperty("http.proxyPort", proxyPort);
            System.setProperty("https.proxyHost", proxyHost);
            System.setProperty("https.proxyPort", proxyPort);
            // 创建一个请求
            Response response = getInstance().newCall(request).execute();
            int httpCode = response.code();
            String result;
            ResponseBody body = response.body();
            if (body != null) {
                result = body.string();
                addResponseLog(httpCode, result, startTime);
            } else {
                throw new Exception("exception in OkHttpUtil,response body is null");
            }
            return handleHttpResponse(httpCode, result);
        } catch (Exception ex) {
            throw new Exception("http请求异常");
        }
    }

    public static String doPost(Request request) throws Exception{
        try {
            long startTime = System.currentTimeMillis();
            // 开启代理
//            String proxyHost = "127.0.0.1";
//            String proxyPort = "7890";
//            System.setProperty("http.proxyHost", proxyHost);
//            System.setProperty("http.proxyPort", proxyPort);
//            System.setProperty("https.proxyHost", proxyHost);
//            System.setProperty("https.proxyPort", proxyPort);
            // 创建一个请求
            Response response = getInstance().newCall(request).execute();
            int httpCode = response.code();
            String result;
            ResponseBody body = response.body();
            if (body != null) {
                result = body.string();
                addResponseLog(httpCode, result, startTime);
            } else {
                throw new Exception("exception in OkHttpUtil,response body is null");
            }
            return handleHttpResponse(httpCode, result);
        } catch (Exception ex) {
            throw new Exception("http请求异常");
        }
    }

    private static void addResponseLog(int httpCode, String result, long startTime) {
        long endTime = System.currentTimeMillis();
    }

    private static String handleHttpResponse(int httpCode, String result) throws Exception {
        if (httpCode == HttpStatus.OK.value()) {
            return result;
        }
        throw new Exception("invalid_token");
    }

    private static void handleHttpThrowable(Exception ex, String url) throws Exception {
        if (ex instanceof Exception) {
            throw (Exception) ex;
        }
        if (ex instanceof SocketTimeoutException) {
            throw new RuntimeException("request time out of OkHttp when do url:" + url);
        }
        throw new RuntimeException(ex);
    }

}

以上是关于实战:第二十五章:HttpUtil代理的主要内容,如果未能解决你的问题,请参考以下文章

第二十五章-中介者模式

WPF学习第二十五章 日期控件

第二十五章 springboot + hystrixdashboard

第二十五章:使用触发器

第二十五章 Kubernetes部署Promethus集群资源监控

python学习手册:第二十五章——oop