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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值