博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
http请求类库(okHttpClient、restTemplate、flux-webclient)
阅读量:6003 次
发布时间:2019-06-20

本文共 4568 字,大约阅读时间需要 15 分钟。

hot3.png

public final class HttpTest {    public static OkHttpClient httpClient = new OkHttpClient.Builder()            .readTimeout(2, TimeUnit.SECONDS)            .writeTimeout(2, TimeUnit.SECONDS)            .connectTimeout(3, TimeUnit.SECONDS)            .build();    private Map
map = new ConcurrentHashMap
(); private static String URL_FACTOR = FileUtil.readString(new File("D:\\WorkSpace\\url.txt"), "utf-8"); private final static String AUTH_VALULE = FileUtil.readString(new File("D:\\WorkSpace\\auth.txt"), "utf-8"); private final static List
IMEIS = Files.linesOf(new File("D:\\WorkSpace\\param.txt"), "utf-8"); /** * 先指定工作目录,不然会超时告警 * @throws IOException */ @Test public void test01() throws IOException { AtomicInteger atomicInteger = new AtomicInteger(); long stratTime = System.currentTimeMillis(); for(String imei : this.IMEIS){// getResponseDataByWebClient(imei, this.map);// getResponseDate(imei, this.map); getResponseByRestTemplate(imei, this.map); atomicInteger.getAndIncrement(); if (atomicInteger.get() == 20){ break; } } System.out.println("查询耗时:" + (System.currentTimeMillis() - stratTime)); System.out.println("查得量: " + map.size()); } // ========= okhttpclient test public void getResponseDate(String imei, Map
map) throws IOException { String url = URL_FACTOR.replace("{imei}", URLEncoder.encode(imei, "UTF-8")); Request request = new Request.Builder() .url(url) .addHeader("Authorization", AUTH_VALULE) .get() .build(); Response response = httpClient.newCall(request).execute(); String string = response.body().string(); Map
data = JSON.parseObject(string).getObject("data", Map.class); if(data != null){ map.putAll(data); } } // ========= webclient test private static WebClient webClient = WebClient.builder().baseUrl("http://host:port").build(); private static String requestPath = "uri{param}"; public void getResponseDataByWebClient(String imei, Map
map) throws UnsupportedEncodingException { String uri = requestPath.replace("{param}", URLEncoder.encode(imei, "UTF-8")); String response = webClient .get() .uri(uri) .header(HttpHeaders.AUTHORIZATION, AUTH_VALULE)// .exchange()// .block(Duration.ofSeconds(3)).bodyToFlux(String.class).blockFirst();// .flatMap(clientResponse -> clientResponse.bodyToMono(String.class)).block(); .retrieve().bodyToMono(String.class).block();// Map
data = JSON.parseObject(response).getObject("data", Map.class); if (data != null){ map.putAll(data); } } // ========= restTemplate test private static RestTemplate restTemplate = new RestTemplate(); public void getResponseByRestTemplate(String imei, Map
map) throws UnsupportedEncodingException { String url = URL_FACTOR.replace("{param}", URLEncoder.encode(imei, "UTF-8")); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add(HttpHeaders.AUTHORIZATION, AUTH_VALULE); httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); HttpEntity
requestEntity = new HttpEntity<>(null, httpHeaders); String resp = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class).getBody(); Map
data = JSON.parseObject(resp).getObject("data", Map.class); if (data != null){ map.putAll(data); } } @Test public void test03() throws IOException { String url = "www.baidu.com"; Request request = new Request.Builder() .url(url) .get() .build(); Response response = httpClient.newCall(request).execute(); String data = response.body().string(); System.out.println(data); } static class FileUtil{ public static String readString(File file, String charsetName){ InputStream inputStream = null; InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; try { inputStream = new FileInputStream(file); inputStreamReader = new InputStreamReader(inputStream); bufferedReader = new BufferedReader(inputStreamReader); return bufferedReader.readLine(); } catch (Exception e) { e.printStackTrace(); }finally { try { bufferedReader.close(); inputStreamReader.close(); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } }}

总结: 

1、单线程下效率比较  okhttpclient  > restTemplate(不包含异步) > flux-webclient

2、异步比较未测试    预计  flux-webclient > okhttpclient > restTemplate (不包含异步)

转载于:https://my.oschina.net/u/3744350/blog/1847919

你可能感兴趣的文章
python实现汉诺塔
查看>>
centos7安装 jupyter
查看>>
MySQL高可用架构之MHA
查看>>
在使用Windows时防止电脑死机的技巧
查看>>
Druid Monitor监控JavaSE和JavaWeb
查看>>
voip工程项目介绍
查看>>
我的友情链接
查看>>
DataTable创建行和列,DataReader读取
查看>>
我的友情链接
查看>>
bat记录远程桌面连接登录信息
查看>>
英勇行动海豹突击队 感
查看>>
我的友情链接
查看>>
ActiveMQ集群应用
查看>>
Exchange Server 2010系列之十七:运维中的故障诊断小工具的使用简介
查看>>
centos7安装指定版本docker且使用本地docker 仓库
查看>>
JAVA学习笔记之常用列表(备查询)
查看>>
使用Storyboard进行界面跳转及传值
查看>>
MVC 3.0 搞笑网站
查看>>
webstorm启动vue项目配置
查看>>
Spring Bood 配置OAuth2 ClientDetailsServiceConfigurer
查看>>