Tuesday 6 July 2021

Apache HTTP Client: set timeout

Step 1: Define Request configuration.

RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
requestConfigBuilder.setConnectTimeout(3 * 1000);
requestConfigBuilder.setConnectionRequestTimeout(3 * 1000);
requestConfigBuilder.setSocketTimeout(3 * 1000);
RequestConfig requestConfig = requestConfigBuilder.build();

 

Step 2: Define an instance of HttpRequestBase and set the request configuration defined in step 1.

 

HttpRequestBase httpget = new HttpGet(url);
httpget.setConfig(requestConfig);

 

Step 3: Execute the request using http client.

CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = httpclient.execute(httpget);

 

Step 4: Get the response as string.

public static String getResponseAsString(CloseableHttpResponse closeableHttpResponse)
		throws UnsupportedOperationException, IOException {

	HttpEntity httpEntity = closeableHttpResponse.getEntity();
	return getResponseAsString(httpEntity.getContent());

}

public static String getResponseAsString(InputStream is) throws IOException {
	try (InputStreamReader isReader = new InputStreamReader(is)) {
		BufferedReader reader = new BufferedReader(isReader);
		StringBuffer sb = new StringBuffer();
		String str;
		while ((str = reader.readLine()) != null) {
			sb.append(str);
		}

		return sb.toString();
	}

}

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment