我可以尝试哪些HttpClient风格可以执行url并以String形式获取响应?

时间:2014-07-14 22:20:12

标签: java performance httpclient resttemplate

我有一个非常简单的要求 - 我需要执行一个URL并将数据作为字符串返回,然后按原样返回该字符串。截至目前,我正在使用RestTemplate拨打电话,因为我需要将标头值传递给我的服务网址。

以下是我目前使用的RestTemplate示例。我在多线程环境中使用RestTemplate。我使用下面代码的项目非常关键,所以我们没有对JSON字符串进行任何反序列化,我们只返回我们从服务器获取的字符串。

RestTemplate restTemplate = new RestTemplate();

HttpHeaders headerInfo = new HttpHeaders();
headerInfo.add("Client-Context", "some-value");
HttpEntity<Object> entity = new HttpEntity<Object>(headerInfo);

String response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
// return this  response back to customer

与RestTemplate相比,我可以尝试使用其他替代方案而不是使用RestTemplate,这将更快更有效吗?我认为与其他HttpClient相比,性能可能相同,但我仍然希望在我的结尾尝试一下,看看性能会有什么不同。

使用替代解决方案的任何示例也会对我有所帮助。

1 个答案:

答案 0 :(得分:1)

您可以使用Apache HTTP Client。它提供了线程池和一些使开箱即用的功能更加简单的功能。它可能不会比你现在使用的更高效,但你可以测试它是肯定的。它看起来像这样(httpClient是您决定和配置的HttpClient的实现):

HttpUriRequest request = new HttpGet("some-url");
request.addHeader("Client-Context", "some-value");
HttpResponse response = httpClient.execute(request);
return IOUtils.toString(response.getEntity().getContent(), "UTF-8");

你也可以使用Java URLs,这是更多的准系统:

URL url = new URL("some-url");
URLConnection con = url.openConnection();
con.setRequestProperty("Client-Context", "some-value");
return IOUtils.toString(con.getInputStream(), "UTF-8");

当然,对于上述两个示例,您需要决定如何处理异常并将InputStream转换为StringIOUtils.toString()是一个选项)。