項目需求:
jsonp是從前臺js的角度考慮,經過Ajax調用springMVC的接口。同一個ip、同一個網絡協議、同一個端口,三者都知足就是同一個域,不然就是跨域問題了。首頁廣告須要一個輪播的效果,取後臺數據json格式。上篇博客介紹了使用jsonp來解決跨域,如今有個新的方法來解決,那就是:ajax請求地址改成本身系統的後臺地址,以後在本身的後臺用HttpClient請求url。封裝好的跨域請求url工具類。封裝一個get一個POST便可。html
二者的區別就在於,jsonp是基於客戶端的跨域解決。而httpclient是基於服務端的跨域解決。java
我如今有兩個maven項目:node
Taotao-portal(8082端口)
Taotao-rest(8081端口)ajax
要使用httpclient須要在maven中引用(portal):spring
-
- <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層提供的服務。apache
httpclient工做圖解:
核心代碼展現:
(portal項目)contentcontroller.javajson
- @Controller
- public class ContentController {
- @Autowired
- private ContentService contentService;
-
-
- @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) {
-
-
- CloseableHttpClient httpclient = HttpClients.createDefault();
-
- String resultString = "";
- CloseableHttpResponse response = null;
- try {
-
- URIBuilder builder = new URIBuilder(url);
- if (param != null) {
- for (String key : param.keySet()) {
- builder.addParameter(key, param.get(key));
- }
- }
- URI uri = builder.build();
-
-
- HttpGet httpGet = new HttpGet(uri);
-
-
- response = httpclient.execute(httpGet);
-
- 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) {
-
- CloseableHttpClient httpClient = HttpClients.createDefault();
- CloseableHttpResponse response = null;
- String resultString = "";
- try {
-
- 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);
- }
-
- response = httpClient.execute(httpPost);
- resultString = EntityUtils.toString(response.getEntity(), "utf-8");
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- response.close();
- } catch (IOException e) {
-
- e.printStackTrace();
- }
- }
-
- return resultString;
- }
-
- public static String doPost(String url) {
- return doPost(url, null);
- }
-
- public static String doPostJson(String url, String json) {
-
- CloseableHttpClient httpClient = HttpClients.createDefault();
- CloseableHttpResponse response = null;
- String resultString = "";
- try {
-
- HttpPost httpPost = new HttpPost(url);
-
- StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
- httpPost.setEntity(entity);
-
- response = httpClient.execute(httpPost);
- resultString = EntityUtils.toString(response.getEntity(), "utf-8");
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- response.close();
- } catch (IOException e) {
-
- 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 {
-
-
- @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() {
-
- String json = HttpClientUtil.doGet(REST_BASE_URL + REST_CONTENT_URL + REST_CONTENT_AD1_CID);
-
- TaotaoResult taotaoResult = TaotaoResult.formatToList(json, TbContent.class);
-
- List<TbContent> contentList = (List<TbContent>) taotaoResult.getData();
-
- 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);
- }
-
- 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";
}
查看網頁源代碼,能夠看到傳過來的json格式的數據。網絡
總結:
HttpClient與Jsonp可以輕易的解決跨域問題,從而獲得本身想要的數據(來自不一樣IP,協議,端口),惟一的不一樣點是,HttpClient是在Java代碼中進行跨域訪問,而Jsonp是在js中進行跨域訪問。跨域還有一級跨域,二級跨域,更多內容值得研究。
app