c httpclient 跨域可以实现跨域请求吗

WebApi系列~通过HttpClient来调用WebApi接口_百度文库
两大类热门资源免费畅读
续费一年阅读会员,立省24元!
WebApi系列~通过HttpClient来调用WebApi接口
阅读已结束,下载文档到电脑
想免费下载更多文档?
定制HR最喜欢的简历
下载文档到电脑,方便使用
还剩2页未读,继续阅读
定制HR最喜欢的简历
你可能喜欢2017年2月 总版技术专家分月排行榜第三
2017年5月 .NET技术大版内专家分月排行榜第一2017年4月 .NET技术大版内专家分月排行榜第一2017年3月 .NET技术大版内专家分月排行榜第一2017年2月 .NET技术大版内专家分月排行榜第一2016年10月 .NET技术大版内专家分月排行榜第一2016年8月 .NET技术大版内专家分月排行榜第一2016年7月 .NET技术大版内专家分月排行榜第一
匿名用户不能发表回复!|
每天回帖即可获得10分可用分!小技巧:
你还可以输入10000个字符
(Ctrl+Enter)
请遵守CSDN,不得违反国家法律法规。
转载文章请注明出自“CSDN(www.csdn.net)”。如是商业用途请联系原作者。跨域Servlet调用Servlet的实现_Linux编程_Linux公社-Linux系统门户网站
你好,游客
跨域Servlet调用Servlet的实现
来源:Linux社区&
作者:lavasoft
跨域Servlet调用Servlet的实现
跨域后,Servlet容器之间彼此是未知的环境,也不能获取到对方的ServetContext。因此使用内部跳转和重定向(需要带请求参数)调用都是错误的,也是无效的。
通过HttpClinet模拟发起请求,可以实现跨域Servlet调用Servlet。
实现方法:在Servlet的service方法中创建httpclient对象,来发起第二次请求。将请求转发个另一个域的servlet。
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
& & & //todo:执行第一个请求的处理
& .......&
//发出第二次请求,调用第二个Servert:postRemotetUrl& //建立HTTP请求& HttpClient httpClient = new DefaultHttpClient();& //注册证书& httpClient.getConnectionManager().getSchemeRegistry().register(sch);& //设置请求超时时间& httpClient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, 20000);& //设置连接超时时间& httpClient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 30000);& & //建立POST请求& HttpPost httpPost = new HttpPost(postRemotetUrl);& httpPost.setEntity(new StringEntity(msg));
& //提交httppost请求& HttpResponse httpResp = httpClient.execute(httpPost);& httpClient.getConnectionManager().shutdown();& .......
相关阅读:
配置Struts2后如何使用Servlet
通过http传输文件到Servlet
Servlet 调用 Spring 容器的 service
使用 Spring 容器管理 Servlet
WAS Websphere下新增Servlet无法访问的问题
相关资讯 & & &
& (10月25日)
& (05月08日)
& (11月24日)
& (06月06日)
& (03月28日)
   同意评论声明
   发表
尊重网上道德,遵守中华人民共和国的各项有关法律法规
承担一切因您的行为而直接或间接导致的民事或刑事法律责任
本站管理人员有权保留或删除其管辖留言中的任意内容
本站有权在网站内转载或引用您的评论
参与本评论即表明您已经阅读并接受上述条款httpclient:是Apache工具包,util,它可以作为一个爬虫,直接爬取某个互联网上的页面。获取到时页面最终的源文件html。直接可以获取页面返回json。就可以直接在代码内部模拟发起http请求。请求的结果也被捕捉。在代码内部将获取的json,利用JacksonObjectMapper对象,把json字符串转成java对象。
与Spring框架整合:
1、引入jar支持
&!-- httpclient --&
&dependency&
&groupId&org.apache.httpcomponents&/groupId&
&artifactId&httpclient&/artifactId&
&version&4.3.5&/version&
&/dependency&
&dependency&
&groupId&org.apache.httpcomponents&/groupId&
&artifactId&httpmime&/artifactId&
&version&4.3.1&/version&
&/dependency&
2、applicationContext-httpclient.xml:
&?xml version="1.0" encoding="UTF-8"?&
&beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"&
&!-- 定义httpclient连接池 --&
&bean id="httpClientConnectionManager" class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager" destroy-method="close"&
&!-- 设置连接总数 --&
&property name="maxTotal" value="${http.pool.maxTotal}"&&/property&
&!-- 设置每个地址的并发数 --&
&property name="defaultMaxPerRoute" value="${http.pool.defaultMaxPerRoute}"&&/property&
&!-- 定义 HttpClient工厂,这里使用HttpClientBuilder构建--&
&bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder" factory-method="create"&
&property name="connectionManager" ref="httpClientConnectionManager"&&/property&
&!-- 得到httpClient的实例 --&
&bean id="httpClient" factory-bean="httpClientBuilder" factory-method="build"/&
&!-- 定期清理无效的连接 --&
&bean class="mon.util.IdleConnectionEvictor" destroy-method="shutdown"&
&constructor-arg index="0" ref="httpClientConnectionManager" /&
&!-- 间隔一分钟清理一次 --&
&constructor-arg index="1" value="600000" /&
&!-- 定义requestConfig的工厂 --&
&bean id="requestConfigBuilder" class="org.apache.http.client.config.RequestConfig.Builder"&
&!-- 从连接池中获取到连接的最长时间 --&
&property name="connectionRequestTimeout" value="${http.request.connectionRequestTimeout}"/&
&!-- 创建连接的最长时间 --&
&property name="connectTimeout" value="${http.request.connectTimeout}"/&
&!-- 数据传输的最长时间 --&
&property name="socketTimeout" value="${http.request.socketTimeout}"/&
&!-- 提交请求前测试连接是否可用 --&
&property name="staleConnectionCheckEnabled" value="${http.request.staleConnectionCheckEnabled}"/&
&!-- 得到requestConfig实例 --&
&bean id="requestConfig" factory-bean="requestConfigBuilder" factory-method="build" /&
3、把httpClient对象封装成伪service。在程序中注入,封装doGet,doPost,doJson- & &---- HttpClientService:
package mon.
import java.util.ArrayL
import java.util.L
import java.util.M
import org.apache.http.NameValueP
import org.apache.http.client.config.RequestC
import org.apache.http.client.entity.UrlEncodedFormE
import org.apache.http.client.methods.CloseableHttpR
import org.apache.http.client.methods.HttpG
import org.apache.http.client.methods.HttpP
import org.apache.http.client.utils.URIB
import org.apache.http.entity.StringE
import org.apache.http.impl.client.CloseableHttpC
import org.apache.http.message.BasicNameValueP
import org.apache.http.util.EntityU
import org.slf4j.L
import org.slf4j.LoggerF
import org.springframework.beans.factory.annotation.A
import org.springframework.stereotype.S
public class HttpClientService {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientService.class);
@Autowired(required=false)
private CloseableHttpClient httpC
@Autowired(required=false)
private RequestConfig requestC
* 执行get请求
* @param url
* @throws Exception
public String doGet(String url,Map&String, String& params,String encode) throws Exception {
("执行GET请求,URL = {}", url);
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();
// 创建http GET请求
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig);
CloseableHttpResponse response = null;
// 执行请求
response = httpClient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
if(encode == null){
encode = "UTF-8";
return EntityUtils.toString(response.getEntity(), encode);
} finally {
if (response != null) {
response.close();
// 此处不能关闭httpClient,如果关闭httpClient,连接池也会销毁
return null;
public String doGet(String url, String encode) throws Exception{
return this.doGet(url, null, encode);
public String doGet(String url) throws Exception{
return this.doGet(url, null, null);
* 带参数的get请求
* @param url
* @param params
* @throws Exception
public String doGet(String url, Map&String, String& params) throws Exception {
return this.doGet(url, params, null);
* 执行POST请求
* @param url
* @param params
* @throws Exception
public String doPost(String url, Map&String, String& params,String encode) throws Exception {
// 创建http POST请求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
if (null != params) {
// 设置2个post参数,一个是scope、一个是q
List&NameValuePair& parameters = new ArrayList&NameValuePair&(0);
for (Map.Entry&String, String& entry : params.entrySet()) {
parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
// 构造一个form表单式的实体
UrlEncodedFormEntity formEntity = null;
if(encode!=null){
formEntity = new UrlEncodedFormEntity(parameters,encode);
formEntity = new UrlEncodedFormEntity(parameters);
// 将请求实体设置到httpPost对象中
httpPost.setEntity(formEntity);
CloseableHttpResponse response = null;
// 执行请求
response = httpClient.execute(httpPost);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity(), "UTF-8");
} finally {
if (response != null) {
response.close();
return null;
* 执行POST请求
* @param url
* @param params
* @throws Exception
public String doPost(String url, Map&String, String& params) throws Exception {
// 创建http POST请求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
if (null != params) {
// 设置2个post参数,一个是scope、一个是q
List&NameValuePair& parameters = new ArrayList&NameValuePair&(0);
for (Map.Entry&String, String& entry : params.entrySet()) {
parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
// 构造一个form表单式的实体
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
// 将请求实体设置到httpPost对象中
httpPost.setEntity(formEntity);
CloseableHttpResponse response = null;
// 执行请求
response = httpClient.execute(httpPost);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity(), "UTF-8");
} finally {
if (response != null) {
response.close();
return null;
public String doPostJson(String url, String json) throws Exception {
// 创建http POST请求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
if(null != json){
//设置请求体为 字符串
StringEntity stringEntity = new StringEntity(json,"UTF-8");
httpPost.setEntity(stringEntity);
CloseableHttpResponse response = null;
// 执行请求
response = httpClient.execute(httpPost);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity(), "UTF-8");
} finally {
if (response != null) {
response.close();
return null;
4、在程序中注入httpClientService,直接调用doGet。
5、在applicationContext.xml中加入&value&classpath:httpclient.properties&/value&
  httpclient.properties:
#从连接池中获取到连接的最长时间
http.request.connectionRequestTimeout=500
http.request.connectTimeout=5000
#数据传输的最长时间
http.request.socketTimeout=30000
#提交请求前测试连接是否可用
http.request.staleConnectionCheckEnabled=true
#设置连接总数
http.pool.maxTotal=200
#设置每个地址的并发数
http.pool.defaultMaxPerRoute=100
阅读(...) 评论()}

我要回帖

更多关于 httpclient跨域 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信