1.先写个工具类:
public class HttpUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtil.class);
public static final String UTF8 = "UTF-8";
public static String getWithTimeout(final String url,int connectTimeout,int connectionRequestTimeout,int socketTimeout)
throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom()
//设置连接超时的时间
.setConnectTimeout(connectTimeout)
//设置从连接池里获取连接超时的时间
.setConnectionRequestTimeout(connectionRequestTimeout)
//传递数据的超时时间
.setSocketTimeout(socketTimeout)
.build();
httpGet.setConfig(requestConfig);
return execute(httpclient,httpGet, UTF8);
}
private static String execute(final HttpClient httpclient, final HttpUriRequest request, final String charset)
throws IOException {
if (LOGGER.isDebugEnabled()) {
}
HttpResponse response = null;
try {
response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
int statusCode = response.getStatusLine().getStatusCode();
String body = EntityUtils.toString(entity, charset);
if (statusCode == HttpStatus.SC_OK) {
return body;
}
else {
throw new RuntimeException(String.valueOf(statusCode));
}
}
else {
throw new IOException("get null content for this request");
}
}
catch (ClientProtocolException e) {
LOGGER.error("ClientProtocolException:{}..{}", request.getProtocolVersion(),e.getMessage());
throw e;
}
finally {
// httpclient.getConnectionManager().shutdown();
if (response != null) {
EntityUtils.consume(response.getEntity()); // 会自动释放连接
}
}
}
}
2.接口中调用:
@GetMapping("/test_http_client")
public List<String> testHttpClient(int connectTimeout,int connectionRequestTimeout,int socketTimeout){
String url = "http://192.168.48.151:10188/box_api/integration/2.0/queryRecentlyWatched?uid=19467660";
List<String> object = null;
try {
String result = HttpUtil.getWithTimeout(url, connectTimeout, connectionRequestTimeout, socketTimeout);
JSONObject jsonObject = JSON.parseObject(result);
JSONArray data = jsonObject.getJSONArray("data");
object = JSON.parseArray(JSON.toJSONString(data),String.class);
} catch (IOException e) {
log.info("testRest请求超时,uid={}",19467660);
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
return object;
}