HTTPClient现在也是Apache下的产品,基于HttpCore,我们可以使用它解决跨域问题。
我们可以在其官方提供的知道文档里参考学习(http://hc.apache.org/httpcomponents-client-ga/tutorial/pdf/httpclient-tutorial.pdf)
将官方提供的API进行总结一下,主要步骤如下:
(1)创建一个CloseableHttpClient实例;
(2)找一个可用的链接(uri);
(3)执行httpclient.execute(uri);
(4)response.close();
官方给出的例子:
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost/");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
<...>
} finally {
response.close();
}
其中,如果放到spring中的话,实例化CloseableHttpClient可以这样:
@Autowired(required=false)
private CloseableHttpClient httpClient;
然后在spring里建一个xml文件专门用于httpClient
关于URI的创建,官方提供了专门的api:
HttpClient provides URIBuilder utility class to simplify creation and modification of request URIs
URI uri = new URIBuilder()
.setScheme("http")
.setHost("www.google.com")
.setPath("/search")
.setParameter("q", "httpclient")
.setParameter("btnG", "Google Search")
.setParameter("aq", "f")
.setParameter("oq", "")
.build();
HttpGet httpget = new HttpGet(uri);
HttpEntity entity = response.getEntity();
有了上面的实例,我们已经可以进行日常的跨域请求了
这里有一个get请求的实例:
public String doGet(String url,Map<String, String> params,String encode) throws Exception {
if(null != params){
URIBuilder builder = new URIBuilder(url);
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.setParameter(entry.getKey(), entry.getValue());
}
url = builder.build().toString();
}
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
if(encode == null){
encode = "UTF-8";
}
return EntityUtils.toString(response.getEntity(), encode);
}
} finally {
if (response != null) {
response.close();
}
}
return null;
}