http请求类库(okHttpClient、restTemplate、flux-webclient)

2019独角兽企业重金招聘Python工程师标准>>> 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

你可能感兴趣的:(http请求类库(okHttpClient、restTemplate、flux-webclient))