如何固定响应时间以在 java 中调用 REST API?

How to fixed response time to call REST API in java?

我想通过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.

响应持续时间的时间限制

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);

您可以使用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/

如果您使用的是 httpClient,以下 link 可以帮助您理解您的问题。 .

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);