使用Httpclient 完美解决服务端跨域问题
项目需求:
jsonp是从前台js的角度考虑,通过Ajax调用springMVC的接口。同一个ip、同一个网络协议、同一个端口,三者都满足就是同一个域,否则就是跨域问题了。首页广告需要一个轮播的效果,取后台数据json格式。上篇博客介绍了使用jsonp来解决跨域,现在有个新的方法来解决,那就是:ajax请求地址改为自己系统的后台地址,之后在自己的后台用HttpClient请求url。封装好的跨域请求url工具类。封装一个get一个POST即可。
两者的区别就在于,jsonp是基于客户端的跨域解决。而httpclient是基于服务端的跨域解决。
我现在有两个maven项目:
Taotao-portal(8082端口)
Taotao-rest(8081端口)
要使用httpclient需要在maven中引用(portal):
- <!-- httpclient -->
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpclient</artifactId>
- </dependency>
<!-- httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
rest项目中写了个后台的服务调广告的数据,在portal项目中的service层来调用rest项目中的controller层提供的服务。
httpclient工作图解:
核心代码展示:
(portal项目)contentcontroller.java
- @Controller
- public class ContentController {
- @Autowired
- private ContentService contentService;
- //getdata
- @RequestMapping("/content/{cid}")
- @ResponseBody
- public TaotaoResult getConentList(@PathVariable Long cid){
- try {
- List<TbContent> list=contentService.getContentList(cid);
- return TaotaoResult.ok(list);
- } catch (Exception e) {
- e.printStackTrace();
- return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
- }
- }
- }
@Controller
public class ContentController {
@Autowired
private ContentService contentService;//getdata
@RequestMapping("/content/{cid}")
@ResponseBody
public TaotaoResult getConentList(@PathVariable Long cid){ try {
List<TbContent> list=contentService.getContentList(cid);
return TaotaoResult.ok(list);
} catch (Exception e) {
e.printStackTrace();
return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
}
}
}
(portal项目)HttpClientUtil.java
- package com.taotao.common.utils;
- import java.io.IOException;
- import java.net.URI;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.CloseableHttpResponse;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.client.utils.URIBuilder;
- import org.apache.http.entity.ContentType;
- import org.apache.http.entity.StringEntity;
- import org.apache.http.impl.client.CloseableHttpClient;
- import org.apache.http.impl.client.HttpClients;
- import org.apache.http.message.BasicNameValuePair;
- import org.apache.http.util.EntityUtils;
- public class HttpClientUtil {
- public static String doGet(String url, Map<String, String> param) {
- // 创建Httpclient对象
- CloseableHttpClient httpclient = HttpClients.createDefault();
- String resultString = "";
- CloseableHttpResponse response = null;
- try {
- // 创建uri
- URIBuilder builder = new URIBuilder(url);
- if (param != null) {
- for (String key : param.keySet()) {
- builder.addParameter(key, param.get(key));
- }
- }
- URI uri = builder.build();
- // 创建http GET请求
- HttpGet httpGet = new HttpGet(uri);
- // 执行请求
- response = httpclient.execute(httpGet);
- // 判断返回状态是否为200
- if (response.getStatusLine().getStatusCode() == 200) {
- resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- if (response != null) {
- response.close();
- }
- httpclient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return resultString;
- }
- public static String doGet(String url) {
- return doGet(url, null);
- }
- public static String doPost(String url, Map<String, String> param) {
- // 创建Httpclient对象
- CloseableHttpClient httpClient = HttpClients.createDefault();
- CloseableHttpResponse response = null;
- String resultString = "";
- try {
- // 创建Http Post请求
- HttpPost httpPost = new HttpPost(url);
- // 创建参数列表
- if (param != null) {
- List<NameValuePair> paramList = new ArrayList<>();
- for (String key : param.keySet()) {
- paramList.add(new BasicNameValuePair(key, param.get(key)));
- }
- // 模拟表单
- UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
- httpPost.setEntity(entity);
- }
- // 执行http请求
- response = httpClient.execute(httpPost);
- resultString = EntityUtils.toString(response.getEntity(), "utf-8");
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- response.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- return resultString;
- }
- public static String doPost(String url) {
- return doPost(url, null);
- }
- public static String doPostJson(String url, String json) {
- // 创建Httpclient对象
- CloseableHttpClient httpClient = HttpClients.createDefault();
- CloseableHttpResponse response = null;
- String resultString = "";
- try {
- // 创建Http Post请求
- HttpPost httpPost = new HttpPost(url);
- // 创建请求内容
- StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
- httpPost.setEntity(entity);
- // 执行http请求
- response = httpClient.execute(httpPost);
- resultString = EntityUtils.toString(response.getEntity(), "utf-8");
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- response.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- return resultString;
- }
- }
package com.taotao.common.utils; import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; public class HttpClientUtil {public static String doGet(String url, Map<String, String> param) { // 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault(); String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build(); // 创建http GET请求
HttpGet httpGet = new HttpGet(uri); // 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
} public static String doGet(String url) {
return doGet(url, null);
} public static String doPost(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} return resultString;
} public static String doPost(String url) {
return doPost(url, null);
} public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} return resultString;
}
}
(rest项目)contentserviceimpl.java
- @Service
- public class ContentServiceImpl implements ContentService {
- //service 写活,读配置文件
- @Value("${REST_BASE_URL}")
- private String REST_BASE_URL;
- @Value("${REST_CONTENT_URL}")
- private String REST_CONTENT_URL;
- @Value("${REST_CONTENT_AD1_CID}")
- private String REST_CONTENT_AD1_CID;
- @Override
- public String getAd1List() {
- //调用服务获得数据 跨域请求:http://localhost:8081/content/89
- String json = HttpClientUtil.doGet(REST_BASE_URL + REST_CONTENT_URL + REST_CONTENT_AD1_CID);
- //把json转换成java对象
- TaotaoResult taotaoResult = TaotaoResult.formatToList(json, TbContent.class);
- //取data属性,内容列表
- List<TbContent> contentList = (List<TbContent>) taotaoResult.getData();
- //把内容列表转换成AdNode列表
- List<AdNode> resultList = new ArrayList<>();
- for (TbContent tbContent : contentList) {
- AdNode node = new AdNode();
- node.setHeight(240);
- node.setWidth(670);
- node.setSrc(tbContent.getPic());
- node.setHeightB(240);
- node.setWidthB(550);
- node.setSrcB(tbContent.getPic2());
- node.setAlt(tbContent.getSubTitle());
- node.setHref(tbContent.getUrl());
- resultList.add(node);
- }
- //需要把resultList转换成json数据
- String resultJson = JsonUtils.objectToJson(resultList);
- return resultJson;
- }
- }
@Service
public class ContentServiceImpl implements ContentService {//service 写活,读配置文件
@Value("${REST_BASE_URL}")
private String REST_BASE_URL;
@Value("${REST_CONTENT_URL}")
private String REST_CONTENT_URL;
@Value("${REST_CONTENT_AD1_CID}")
private String REST_CONTENT_AD1_CID;
@Override
public String getAd1List() {
//调用服务获得数据 跨域请求:http://localhost:8081/content/89
String json = HttpClientUtil.doGet(REST_BASE_URL + REST_CONTENT_URL + REST_CONTENT_AD1_CID);
//把json转换成java对象
TaotaoResult taotaoResult = TaotaoResult.formatToList(json, TbContent.class);
//取data属性,内容列表
List<TbContent> contentList = (List<TbContent>) taotaoResult.getData();
//把内容列表转换成AdNode列表
List<AdNode> resultList = new ArrayList<>();
for (TbContent tbContent : contentList) {
AdNode node = new AdNode();
node.setHeight(240);
node.setWidth(670);
node.setSrc(tbContent.getPic()); node.setHeightB(240);
node.setWidthB(550);
node.setSrcB(tbContent.getPic2()); node.setAlt(tbContent.getSubTitle());
node.setHref(tbContent.getUrl()); resultList.add(node);
}
//需要把resultList转换成json数据
String resultJson = JsonUtils.objectToJson(resultList);
return resultJson;
}
}
(rest项目)indexcontroller
- @Autowired
- private ContentService contentService;
- @RequestMapping("/index")
- public String showIndex(Model model){
- String json=contentService.getAd1List();
- model.addAttribute("ad1",json);
- return "index";
- }
@Autowired
private ContentService contentService;@RequestMapping("/index")
public String showIndex(Model model){
String json=contentService.getAd1List();
model.addAttribute("ad1",json);
return "index";
}</pre><br>
查看网页源代码,可以看到传过来的json格式的数据。
总结:
HttpClient与Jsonp能够轻易的解决跨域问题,从而得到自己想要的数据(来自不同IP,协议,端口),唯一的不同点是,HttpClient是在Java代码中进行跨域访问,而Jsonp是在js中进行跨域访问。跨域还有一级跨域,二级跨域,更多内容值得研究。
使用Httpclient 完美解决服务端跨域问题的更多相关文章
- SharePoint 2013 APP 开发示例 (六)服务端跨域访问 Web Service (REST API)
上个示例(SharePoint 2013 APP 开发示例 (五)跨域访问 Web Service (REST API))是基于JavaScript,运行在web browser内去访问REST AP ...
- 谷歌、火狐浏览器下实现JS跨域iframe高度自适应的完美解决方法,跨域调用JS不再是难题!
谷歌.火狐浏览器下实现JS跨域iframe高度自适应的解决方法 导读:今天开发的时候遇到个iframe自适应高度的问题,相信大家对这个不陌生,但是一般我们都是在同一个项目使用iframe嵌套页面,这个 ...
- 服务端跨域处理 Cors
1 添加 System.Web.Cors,System.Web.Http.Cors 2 global文件中 注册asp.net 管道事件 protected void Application_Beg ...
- CORS服务端跨域
跨域,通常情况下是说在两个不通过的域名下面无法进行正常的通信,或者说是无法获取其他域名下面的数据,这个主要的原因是,浏览器出于安全问题的考虑,采用了同源策略,通过浏览器对JS的限制,防止恶意用户获取非 ...
- .net core api服务端跨域配置
第1步:添加包引用(.net core 2.2 已自带此包,可跳过此步骤) Install-Package Microsoft.AspNetCore.Cors 第2步:在Startup.cs文件的Co ...
- 跨域调用webapi web端跨域调用webapi
web端跨域调用webapi 在做Web开发中,常常会遇到跨域的问题,到目前为止,已经有非常多的跨域解决方案. 通过自己的研究以及在网上看了一些大神的博客,写了一个Demo 首先新建一个webap ...
- Vue Nginx反向代理配置 解决生产环境跨域
Vue本地代理举例: module.exports = { publicPath: './', devServer: { proxy: { '/api': { target: 'https://mov ...
- Nginx配置解决NetCore的跨域
使用Nginx配置解决NetCore的跨域 废话不多说,直接上Nginx配置 server { listen 80; server_name 你的Id或域名; location / { add_hea ...
- SpringCloud微服务Zuul跨域问题
目前项目结构是VUE做前端,后端采用微服务架构,在开发时前端需要跨域请求数据,通过ZuulFilter配置解决了简单跨域请求需要.但当需要在请求的header中增加token信息时,出现了请求失败的情 ...
随机推荐
- 来杭州云栖大会,全面了解企业如何实现云上IT治理
企业上云的现状与趋势 云计算,如今已经成为了像水和电一般关系到国计民生的国家基础设施.云计算为企业带了前所未有的资源交付效率和运维效率的提升,同时也用全新的技术帮助企业在新的价值网络中创造新的商业赛道 ...
- ROC曲线及AUC
ROC曲线 意义 ROC曲线指受试者工作特征曲线 / 接收器操作特性曲线(receiver operating characteristic curve),是反映敏感性和特异性连续变量的综合指标,是用 ...
- JDK1.8 之Lambda表达式
概述 Lambda 表达式是一种匿名函数(对 Java 而言这并不完全正确,但现在姑且这么认为),简单地说,它是没有声明的方法,也即没有访问修饰符.返回值声明和名字. 你可以将其想做一种速记,在你需要 ...
- leetcode 996. Number of Squareful Arrays
给定一个长度小于 12 的数组 要求排列方式的种数 使得相邻和为完全平方 不考虑数学结构 将问题转化为 一笔画问题 和为完全平方代表 之间存在通路 回溯法 N^N 记忆化搜索 NN 2^N 判断是否是 ...
- vue 引入css及注意事项
组件中: <style scoped> @import '../../static/css/xx.css'; // “ :”必须有 </style> 注:若用以下方法,全部组件 ...
- kafka comsumer
kafka的顺序消费只保证在同一个partition中而已
- C++ 静态对象
一:什么是静态对象? 对象的存储方式是静态的. 局部静态对象和类的静态对象. 局部静态对象:一个变量在函数内部定义,其生命周期跨越了该函数的多次调用.局部对象确保不迟于 ...
- PHP CURL 异步测试
需求, 请求第三方接口获取数据, 单个接口0.1秒, 如果有10万个接口, 那么岂不是得1万秒才能请求完, 所以使用PHP异步测试一下, 其他的方法还有: 1.使用队列, SupserVior 开多个 ...
- 你真的了解cookies吗?
互联网隐私安全,直接放链接吧,这一篇非常好的文章,详细,全面,专业. http://www.freebuf.com/articles/web/127266.html 浅谈Web客户端追踪 一. W ...
- charles for https
To remotely capture http or https traffic with charles you will need to do the following: HOST - Mac ...