【问题标题】:How to fixed response time to call REST API in java?如何固定响应时间以在 Java 中调用 REST API?
【发布时间】:2019-02-20 06:03:35
【问题描述】:

我想通过java编程调用REST API。而且我还想在调用该 API 期间给出时间限制。如果响应时间超过 10 秒,我想断开 API 调用并打印响应时间超过 10 秒的消息。

请通过给出的java示例代码帮助我。

下面给出调用API的源代码。

JSONParserPost jsonParserpost = new JSONParserPost();
        String output = jsonParserpost.makeHttpRequest(URL, "POST", request); 
        System.out.println("Row output :"+ output.toString());
        JSONObject jsonObject = new JSONObject(output);
        if(jsonObject != null) 
            responeXML = (String)jsonObject.get("response");

在第 2 行中,我调用了 REST API。现在我想修复 REST API 响应持续时间的时间限制。

【问题讨论】:

标签: java rest api time response


【解决方案1】:

如果您使用的是 httpClient,则以下链接可以帮助您了解我对您的问题的理解。 Apache HttpClient Timeout.

int CONNECTION_TIMEOUT_MS = timeoutSeconds * 1000; // Timeout in millis.
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS)
.setConnectTimeout(CONNECTION_TIMEOUT_MS)
.setSocketTimeout(CONNECTION_TIMEOUT_MS)
.build();

HttpPost httpPost = new HttpPost(URL);
httpPost.setConfig(requestConfig);

【讨论】:

    【解决方案2】:

    1

    URL url = new URL(this.serviceURL);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
    connection.setRequestProperty("Accept", "application/xml;");
    
    connection.setDoInput(true);
    connection.setDoOutput(true);
    
    /*
     * connection timeout value to 20 seconds
     */
    int apiReadTimeOut = 20; // 20 seconds
    connection.setConnectTimeout(apiReadTimeOut * 1000);
    connection.setReadTimeout(apiReadTimeOut * 1000);
    

    2

    HttpClient httpClient = null;
    
    /*
    * connection timeout value to 20 seconds
    */
    final HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000);
    httpClient = new DefaultHttpClient(httpParams);
    

    【讨论】:

      【解决方案3】:

      你可以使用spring restTemplate

         @Bean
          public RestTemplate restTemplate() {
              RestTemplate restTemplate = new RestTemplate();
              ((SimpleClientHttpRequestFactory) restTemplate.getRequestFactory()).setConnectTimeout(milisecond);
              ((SimpleClientHttpRequestFactory) restTemplate.getRequestFactory()).setReadTimeout(milisecond);
      
              return restTemplate;
          }
      

      请查找示例 - https://howtodoinjava.com/spring-boot2/resttemplate-timeout-example/

      【讨论】:

        猜你喜欢
        • 2017-09-03
        • 2018-11-25
        • 2011-01-20
        • 2018-01-07
        • 2011-07-03
        • 2017-09-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多