Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

java - HttpsURLConnection vs RestClient/RestTemplate

We are integrating Client APIs which uses Polling. They provide us sample client, sample code below:

URL url = new URL(sURL);
HttpsURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-type", "application/xml");

// LOGIN Call..

while(true) {
  
  // Write Request
  PrintWriter requestWriter = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
  requestWriter.print(request);
  requestWriter.flush();
  requestWriter.close();

  // Read Response
  BufferedReader responseReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  

   // Evaluate Response
   // ......

   if(statisfied) {
     break;
   }

 }

 // LOGOUT Call..

There're 3 steps in their API, 1) LOGIN, 2) RUN, and 3) LOGOUT. LOGIN return a JSESSIONID, which we use during the RUN process. RUN uses POLLING, after Request Submission, it's keep polling, receives several regular HEARTBEAT responses till the final response comes back. And at the end run, LOGOUT hits to expire the session.

I want to re-write the above code using any modern client like, RestTemplete or else. I tried RestTemplate but unable to keep the connection open properly...

// RestTemplate Configuration
@Bean(name = "restTemplate")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public RestTemplate restTemplate() throws Exception {

    HttpHost proxy = new HttpHost("xxx.xxxx.com", 8080);
    TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();

    PoolingHttpClientConnectionManager poolingConnectionManager = new PoolingHttpClientConnectionManager();
    poolingConnectionManager.setMaxTotal(100);
    poolingConnectionManager.setDefaultMaxPerRoute(50);

    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
    CloseableHttpClient httpClient = HttpClients.custom()
            .setProxy(proxy)
            .setSSLSocketFactory(csf)
            .setConnectionManager(poolingConnectionManager)
            .setConnectionReuseStrategy(new NoConnectionReuseStrategy())
            .setRetryHandler(new RetryHandler(3, true))
            .addInterceptorLast(new ResponseInterceptor())
            .build();

    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);

    RestTemplate restTemplate =
            new RestTemplateBuilder()
                    .setBufferRequestBody(false)
                    .setReadTimeout(Duration.ofSeconds(900))
                    .setConnectTimeout(Duration.ofSeconds(900))
                    .errorHandler(new ResponseErrorHandler())
                    .build();
    restTemplate.setRequestFactory(requestFactory);

    return restTemplate;
}

// RestTemplate Utilitization...
        CompletableFuture<ResponseObject> completableFuture = CompletableFuture.supplyAsync(() -> restTemplate.postForObject(url, entity, ResponseObject.class));
    try {
        while(Objects.nonNull(completableFuture.get())) {
            response = completableFuture.get();
            if(Objects.nonNull(response.getResponse()) && Objects.nonNull(response.getResponse().getFinalResponse())) {
                break;
            }

            Thread.sleep(10000);
            print(response);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

Can anyone guide me how to re-write the above using any modern client. The main question is, how to keep open connection using RestTemplate or any other client? If possible, please share some sample code. thanks

question from:https://stackoverflow.com/questions/65945382/httpsurlconnection-vs-restclient-resttemplate

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...