Java跨域訪問的解決方式

問題:瀏覽器的console:Access to XMLHttpRequest at 'http://localhost:8080/web1/api/getXXX' from origin 'http://127.0.0.1:8088' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

1、設置Header響應頭

  • response.setHeader(“Access-Control-Allow-Origin”, “*”);// *表示所有請求允許跨域
  • response.setHeader(“Access-Control-Allow-Origin”, “http://www.domain1.com”);// 只允許domain1域名訪問

一般是寫在過濾器或者攔截器中

2、使用JSONP

缺點:不支持post請求,代碼書寫比較複雜

<script type="text/javascript">

	$(document).ready(function() {
		$.ajax({
			type : "GET",
			async : false,
			url : "http://localhost:8080/web1/api/getXXX",
			dataType : "jsonp",
			jsonp : "jsonpCallback", //服務端用於接收callback調用的function名的參數 
			success : function(data) {
				alert(data["errorCode"]);
			},
			error : function() {
				alert('fail');
			}
		});
	});
</script>

後端代碼:jsonpCallback 爲jsonp生成的參數

@RequestMapping(value = "/ajaxB", method = RequestMethod.GET)
public void ajaxB(HttpServletResponse response, String jsonpCallback) throws IOException {
		
    JSONObject root = new JSONObject();
    root.put("errorCode", "200");
    root.put("errorMsg", "登陸成功");
		
    response.setHeader("Content-type", "text/html;charset=UTF-8");
    PrintWriter writer = response.getWriter();
    //需要把jsonp生成的參數帶回前臺,jsonp才能解析
    writer.print(jsonpCallback + "(" + root.toString() + ")");
    writer.close();
}

3、Nginx搭建API接口網關

  server {
        listen       80;
        server_name  www.baidu.com;

		###A項目
        location /a {
            proxy_pass   http://a.baidu.com:8080/;
            index  index.html index.htm;
        }
		###B項目
		 location /b {
            proxy_pass   http://b.baidu.com:8081/;
            index  index.html index.htm;
        }
    }

4、HttpClient 轉發

/**
 * @description: 使用httpClient對象執行get請求
 * @param: uri  需要跨域請求的uri
 * @author:wu
 * @throws IOException 
 * @throws ClientProtocolException 
 * @createDate:2018年2月28日 下午2:19:00
 */
public static String  doGet(String uri) throws ClientProtocolException, IOException{
	if(StringUtils.isBlank(uri)){
		uri="http://localhost:8080/web1/api/getXXX";
	}
	// 1、 創建 httpClient 對象
	CloseableHttpClient httpClient = HttpClients.createDefault();
	// 2、 創建 get 對象
	HttpGet get =new HttpGet(uri);
	// 3、 執行 get 請求
	CloseableHttpResponse response = httpClient.execute(get);
	// 4、 獲取返回結果 HttpEntity  對象
	HttpEntity entity = response.getEntity();
	// 5、獲取返回結果中的數據  
	String data = EntityUtils.toString(entity);
	// 6、 關閉 response、 關閉 httpClient
	response.close();
	httpClient.close();
	return data;
}

/**
 * @description:使用httpClient對象執行 post 請求
 * @param: uri 需要跨域請求的uri , formDataMap  模擬表單需要提交數據 (name - value 形式)
 * @author:wu
 * @createDate:2018年2月28日 下午4:36:55
 */
public static String doPost(String uri,Map<String,Object> formDataMap) throws ClientProtocolException, IOException{
	if(StringUtils.isBlank(uri)){
		uri="http://localhost:8080/web1/api/getXXX";
	}
	// 1、創建httpClient 對象
	CloseableHttpClient httpClient = HttpClients.createDefault();
	// 2、 創建post 對象
	HttpPost post =new HttpPost(uri);
	// 3、 創建一個list形式數據,模擬提交表單。 
	List<NameValuePair> formDataList=new ArrayList<>();
	// TODO: 這裏可以遍歷模擬表單傳遞過來的數據 formDataMap
	/*Iterator<Entry<String, Object>> iterator = formDataMap.entrySet().iterator();
	while(iterator.hasNext()){
		Entry<String, Object> next = iterator.next();
		String key = next.getKey();
		String value = next.getValue().toString();
		formDataList.add(new BasicNameValuePair(key, value));
	}*/
	formDataList.add(new BasicNameValuePair("ids", "110"));
	formDataList.add(new BasicNameValuePair("name", "httpClient 請求數據"));
	// 4、 把表單數據包裝到entity 對象中 (StringEntity)
	StringEntity formData = new UrlEncodedFormEntity(formDataList, "UTF-8");
	post.setEntity(formData);
	// 5、 執行post請求
	CloseableHttpResponse response = httpClient.execute(post);
	// 6、 獲取響應數據
	HttpEntity entity = response.getEntity();
	// 7、 響應數據轉換爲字符串
	String data = EntityUtils.toString(entity);
	// 8、 關閉 httpClient對象、關閉 response
	response.close();
	httpClient.close();
	return data;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章