栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

实战:第二十五章: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;




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";

    
    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);
    }

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/397147.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号