分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 代码编程

使用Httpclient 完美解决服务端跨域问题

发布时间:2023-09-06 01:42责任编辑:彭小芳关键词:跨域

项目需求:


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):


[html] view plain copy
print?
  1. <!--httpclient-->
  2. <groupId>org.apache.httpcomponents</groupId>
  3. </dependency>
<!-- httpclient --><dependency> ???<groupId>org.apache.httpcomponents</groupId> ???<artifactId>httpclient</artifactId></dependency>


rest项目中写了个后台的服务调广告的数据,在portal项目中的service层来调用rest项目中的controller层提供的服务。


httpclient工作图解:


核心代码展示:


(portal项目)contentcontroller.java

[java] view plain copy
print?
  1. @Controller
  2. @Autowired
  3. @RequestMapping("/content/{cid}")
  4. publicTaotaoResultgetConentList(@PathVariableLongcid){
  5. try{
  6. returnTaotaoResult.ok(list);
  7. e.printStackTrace();
  8. }
  9. }
@Controllerpublic 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

[java] view plain copy
print?
  1. packagecom.taotao.common.utils;
  2. importjava.io.IOException;
  3. importjava.util.ArrayList;
  4. importjava.util.Map;
  5. importorg.apache.http.NameValuePair;
  6. importorg.apache.http.client.methods.CloseableHttpResponse;
  7. importorg.apache.http.client.methods.HttpPost;
  8. importorg.apache.http.entity.ContentType;
  9. importorg.apache.http.impl.client.CloseableHttpClient;
  10. importorg.apache.http.message.BasicNameValuePair;
  11. CloseableHttpClienthttpclient=HttpClients.createDefault();
  12. StringresultString="";
  13. try{
  14. URIBuilderbuilder=newURIBuilder(url);
  15. for(Stringkey:param.keySet()){
  16. }
  17. URIuri=builder.build();
  18. //创建httpGET请求
  19. response=httpclient.execute(httpGet);
  20. if(response.getStatusLine().getStatusCode()==200){
  21. }
  22. e.printStackTrace();
  23. try{
  24. response.close();
  25. httpclient.close();
  26. e.printStackTrace();
  27. }
  28. }
  29. publicstaticStringdoGet(Stringurl){
  30. }
  31. publicstaticStringdoPost(Stringurl,Map<String,String>param){
  32. CloseableHttpClienthttpClient=HttpClients.createDefault();
  33. StringresultString="";
  34. //创建HttpPost请求
  35. //创建参数列表
  36. List<NameValuePair>paramList=newArrayList<>();
  37. paramList.add(newBasicNameValuePair(key,param.get(key)));
  38. //模拟表单
  39. httpPost.setEntity(entity);
  40. //执行http请求
  41. resultString=EntityUtils.toString(response.getEntity(),"utf-8");
  42. e.printStackTrace();
  43. try{
  44. }catch(IOExceptione){
  45. e.printStackTrace();
  46. }
  47. returnresultString;
  48. returndoPost(url,null);
  49. //创建Httpclient对象
  50. CloseableHttpResponseresponse=null;
  51. try{
  52. HttpPosthttpPost=newHttpPost(url);
  53. StringEntityentity=newStringEntity(json,ContentType.APPLICATION_JSON);
  54. //执行http请求
  55. resultString=EntityUtils.toString(response.getEntity(),"utf-8");
  56. e.printStackTrace();
  57. try{
  58. }catch(IOExceptione){
  59. e.printStackTrace();
  60. }
  61. returnresultString;
  62. }
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
[java] view plain copy
print?
  1. @Service
  2. @Value("${REST_BASE_URL}")
  3. @Value("${REST_CONTENT_URL}")
  4. @Value("${REST_CONTENT_AD1_CID}")
  5. @Override
  6. //调用服务获得数据跨域请求:http://localhost:8081/content/89
  7. //把json转换成java对象
  8. //取data属性,内容列表
  9. //把内容列表转换成AdNode列表
  10. for(TbContenttbContent:contentList){
  11. node.setHeight(240);
  12. node.setSrc(tbContent.getPic());
  13. node.setHeightB(240);
  14. node.setSrcB(tbContent.getPic2());
  15. node.setAlt(tbContent.getSubTitle());
  16. }
  17. StringresultJson=JsonUtils.objectToJson(resultList);
  18. }
  19. @Servicepublic 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
    [java] view plain copy
    print?
    1. @Autowired
    2. publicStringshowIndex(Modelmodel){
    3. model.addAttribute("ad1",json);
    4. }
    @Autowired ???private ContentService contentService; ???????@RequestMapping("/index") ???public String showIndex(Model model){ ???????String json=contentService.getAd1List(); ???????model.addAttribute("ad1",json); ???????return "index"; ???}


    查看网页源代码,可以看到传过来的json格式的数据。



    总结:


    HttpClient与Jsonp能够轻易的解决跨域问题,从而得到自己想要的数据(来自不同IP,协议,端口),唯一的不同点是,HttpClient是在Java代码中进行跨域访问,而Jsonp是在js中进行跨域访问。跨域还有一级跨域,二级跨域,更多内容值得研究。




    ??

使用Httpclient 完美解决服务端跨域问题

原文地址:https://www.cnblogs.com/jpfss/p/8443775.html

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved