項目需求:
jsonp是從前台js的角度考慮,通過Ajax調用springMVC的接口。同一個ip、同一個網絡協議、同一個端口,三者都滿足就是同一個域,否則就是跨域問題了。首頁廣告需要一個輪播的效果,取后台數據json格式。上篇博客介紹了使用jsonp來解決跨域,現在有個新的方法來解決,那就是:ajax請求地址改為自己系統的后台地址,之后在自己的后台用HttpClient請求url。封裝好的跨域請求url工具類。封裝一個get一個POST即可。
兩者的區別就在於,jsonp是基於客戶端的跨域解決。而httpclient是基於服務端的跨域解決。
我現在有兩個maven項目:
Taotao-rest(8081端口)
要使用httpclient需要在maven中引用(portal):
- <!-- 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));
- }
- }
- }
(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;
- }
- }
(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;
- }
- }
(rest項目)indexcontroller
- @Autowired
- private ContentService contentService;
- @RequestMapping("/index")
- public String showIndex(Model model){
- String json=contentService.getAd1List();
- model.addAttribute("ad1",json);
- return "index";
- }