首页 > 其他分享 >http请求方式-OkHttpClient

http请求方式-OkHttpClient

时间:2022-10-13 19:25:46浏览次数:44  
标签:http String url OkHttpClient static new response 请求

http请求方式-OkHttpClient

import com.example.core.mydemo.http.OrderReqVO;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class OkHttpClient {
    private static Logger log = LoggerFactory.getLogger(OkHttpClient.class);

    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    private volatile static okhttp3.OkHttpClient client;

    private static final int MAX_IDLE_CONNECTION = 2;
    private static final long KEEP_ALIVE_DURATION = 2;
    private static final long CONNECT_TIMEOUT = 1000;
    private static final long READ_TIMEOUT = 3000;

    /**
     * 单例模式(双重检查模式) 获取类实例
     *
     * @return client
     */
    private static okhttp3.OkHttpClient getInstance() {
        if (client == null) {
            synchronized (okhttp3.OkHttpClient.class) {
                if (client == null) {
                    client = new okhttp3.OkHttpClient.Builder()
                            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                            .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                            .connectionPool(new ConnectionPool(MAX_IDLE_CONNECTION, KEEP_ALIVE_DURATION,
                                    TimeUnit.MINUTES))
                            .build();
                }
            }
        }
        return client;
    }

    public static String syncPost(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try {
            Response response = OkHttpClient.getInstance().newCall(request).execute();
            if (response.isSuccessful()) {
                String result = response.body().string();
                log.info("syncPost response = {}, responseBody= {}", response, result);
                return result;
            }
            String result = response.body().string();
            log.info("syncPost response = {}, responseBody= {}", response, result);
            throw new IOException("三方接口返回http状态码为" + response.code());
        } catch (Exception e) {
            log.error("syncPost() url:{} have a ecxeption {}", url, e);
            throw new RuntimeException("syncPost() have a ecxeption {}" + e.getMessage());
        }
    }

    public static String syncGet(String url, Map<String, Object> headParamsMap) throws IOException {
        Request request;
        final Request.Builder builder = new Request.Builder().url(url);
        try {
            if (!CollectionUtils.isEmpty(headParamsMap)) {
                final Iterator<Map.Entry<String, Object>> iterator = headParamsMap.entrySet()
                        .iterator();
                while (iterator.hasNext()) {
                    final Map.Entry<String, Object> entry = iterator.next();
                    builder.addHeader(entry.getKey(), (String) entry.getValue());
                }
            }
            request = builder.build();
            Response response = OkHttpClient.getInstance().newCall(request).execute();
            String result = response.body().string();
            log.info("syncGet response = {},responseBody= {}", response, result);
            if (!response.isSuccessful()) {
                throw new IOException("三方接口返回http状态码为" + response.code());
            }
            return result;
        } catch (Exception e) {
            log.error("remote interface url:{} have a ecxeption {}", url, e);
            throw new RuntimeException("三方接口返回异常");
        }
    }

    public static void main(String[] args) {
        OrderReqVO data = new OrderReqVO();
        data.setOrderNum("111123333");
        data.setServerType("1");


        String url = "https://域名/接口名称";

        try {
            String resp = syncPost(url, com.alibaba.fastjson.JSON.toJSONString(data));
            System.out.println("resp = " + resp);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

 

标签:http,String,url,OkHttpClient,static,new,response,请求
From: https://www.cnblogs.com/oktokeep/p/16789349.html

相关文章

  • http请求方式-RestTemplate
    http请求方式-RestTemplateimportcom.alibaba.fastjson.JSON;importcom.example.core.mydemo.http.OrderReqVO;importorg.springframework.http.HttpEntity;import......
  • http请求方式-CloseableHttpClient
    http请求方式-CloseableHttpClientimportcom.alibaba.fastjson.JSON;importcom.alibaba.fastjson.JSONObject;importcom.example.core.mydemo.http.OrderReqVO;imp......
  • http请求方式-HttpClient
    http请求方式-HttpClientimportcom.alibaba.fastjson.JSON;importcom.alibaba.fastjson.JSONObject;importcom.example.core.mydemo.http.OrderReqVO;importorg.a......
  • http请求方式-HttpURLConnection
    http请求方式-HttpURLConnectionimportcom.alibaba.fastjson.JSON;importcom.example.core.mydemo.http.OrderReqVO;importorg.springframework.lang.Nullable;im......
  • scrapy 给单个请求设置超时时间
       meta={'download_timeout':30}     ......
  • http 报文
    一、报文格式:一个HTTP请求报文由请求行(requestline)、请求头部(header)、空行和请求数据4个部分组成,具体格式如下;1.请求报文格式起始行<method>      空格   <r......
  • uni-app发送GET和POST请求方式
    基于上一篇文章对AJAX概念的描述,那么目前流行的uni-app到底是怎么发请求的呢,我会把格式写在下面使用uni.request()发起GET请求:使用uni.request()发起POST请求let......
  • python requests库提示警告:InsecureRequestWarning: Unverified HTTPS request is bei
    在利用requests访问链接,有时有有警告InsecureRequestWarning:UnverifiedHTTPSrequestisbeingmade.Addingcertificatever解决办法:Python3访问HT......
  • watch 监视搜索关键词的变化不断发送请求返回建议
    watch:{keywords:{//yarnaddlodash下载lodash包//import{debounce}from"lodash";引入防抖的函数//每隔700ms执行一次handler......
  • 【HTTP】190-http 状态码竟然可以这样记
    标题皮了一下,但是内容应该算是比较用心的,不是直接抄了一下官方文档和一堆抽象的术语,尽量配合实例解释的通俗一些。基本介绍状态码(StatusCode)和原因短语(ReasonPhrase)用于简......