jsonp跨域,cors跨域分享以及HttpClient跨域

     最近开发项目,需要跨域访问别人家的接口。



    于是在此相对,在这次开发中的跨域问题做个总结。



1.最开始用的是JSONP,JSONP大家应该也都比较熟悉,

$.ajax({	
			url: url,
			method: 'POST',
			dataType: 'jsonp',
		    jsonp: 'callback',
		    jsonpCallback: 'callbackFunction',
			data:{saruLruid:saruLruid,transAmt:transAmt...
				
			},
			success: function(data){
				if(data.resultCode == 0) {
					orderNum=data.orderNo; 
					window.location.href="phoneCode.jsp?orderNum="+orderNum;
				} else {
					alert(data.errorMsg);
				}				
			},
			error: function(data) {
			}
		});


  用jsonp  可以很成功的跨域访问,但是有一个很重要的问题。  

  就是对方 返回的数据 必须是 如下格式: callbackFunction(json); 这样的格式,  这边的callbackFunction 就是我们 在ajax 那设置的 jsonpcallback 函数名。 只有这样我们才能成功的 接收到对方返回回来的数据。不然就会报Uncaught SyntaxError: Unexpected token . 

所以如果用jsonp实现跨域最好是对方的接口是你们自己人提供的可以给予你修改的否则还是考虑HttpClient跨域。

2.HttpClient跨域

要用 这个 得 先导入包 

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>

    

                // 创建 HttpClient 的实例  
                HttpClient httpClient = new HttpClient(); 
        		response.setCharacterEncoding("utf-8");
        		response.setContentType("text/json");
                //获得跳转地址  
        		String realname = URLEncoder.encode("陈江华", "UTF-8");
        		String tm = new Date().getTime()+"";  
        		String url = "http://121.41.42.121:8080/v3/card4-server";
        		PostMethod postMethod = new PostMethod(url);    
                   //这部很重要,这样传入的中文参数才能正确的被识别
        		postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
        //添加函数
        postMethod.addParameter("mall_id", mall_id);  
        postMethod.addParameter("sign", sign);
        // 执行postMethod  
        int statusCode = httpClient.executeMethod(postMethod);  
        //输出回应  
        InputStream is = postMethod.getResponseBodyAsStream();  
        BufferedReader br = new BufferedReader(new InputStreamReader(is,  
                "utf-8"));  
        String line = "";  
        JSONObject json = new JSONObject();
        while ((line = br.readLine()) != null) {  
        	json= (JSONObject) JSON.parse(line);//在这边将对方接口返回的数据转为json 
            System.out.println(line);  
        }  

      //查看缓存  
   /*     Cookie[] cookies = httpClient.getState().getCookies();  
        System.out.println("cookies length = " + cookies.length + "    state="    
                   + statusCode);                                                         
        for (int i = 0; i < cookies.length && cookies.length!=0; i++) {                                
            System.out.println("cookie - " + i + ":");                            
            System.out.println(cookies.toString());                               
            System.out.println(cookies[i].getDomain());                           
            System.out.println(cookies[i].getName());                             
            System.out.println(cookies[i].getPath());                             
            System.out.println(cookies[i].getValue());                            
            System.out.println("---------------------");                          
        }  
        int a = HttpStatus.SC_OK;  
                 
        Map m = new HashMap();  */
        // HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发  
        // 301或者302  
    /*    if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY  
                || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {  
            Header header = (Header) postMethod.getResponseHeader("location");  
            String location = null;  
            if (header != null) {  
                location = header.getValue();  
                System.out.println("aaaaaaaa" + location);  
                if((location == null) || location.equals("")){  
                    location = "/";  
                }  
                GetMethod redirect = new GetMethod(location);  
                httpClient.executeMethod(redirect);  
                redirect.releaseConnection();  
                                //存放最终跳转的链接  
                m.put("dispatchUrl", location);  
            }else{  
            }  
            postMethod.releaseConnection();  

return  json.toJSONStringl;


    3.接下来要讲的是 cors跨域.

    cors跨域资源分享。我的理解是将资源分享给别人,允许别人可以跨域访问你。

  我 之前没搞懂是这个意思,一直搞这个就在想怎么都跨域访问不了别人。最后才知道是允许别人访问你。


用使用这个很简单, 只要在web.xml  加上如下配置


<!-- CORS过滤器 start -->  
<!-- <filter>  
    <filter-name>cors</filter-name>  
    <filter-class>com.pay.filter.CorsFilter</filter-class>  
</filter>  
<filter-mapping>  
    <filter-name>cors</filter-name>  
    <url-pattern>/api/*</url-pattern>  
</filter-mapping>   -->
<!-- CORS过滤器 end -->

然后

@Component  
public class CorsFilter implements Filter {  
  
    @Override  
    public void init(FilterConfig filterConfig) throws ServletException {  
  
    }  
  
    @Override  
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {  
        HttpServletResponse response = (HttpServletResponse) servletResponse;  
        response.setHeader("Access-Control-Allow-Origin", "*");  
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");  
        response.setHeader("Access-Control-Max-Age", "3600");  
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");  
        response.setHeader("Access-Control-Allow-Credentials", "true");  
        filterChain.doFilter(servletRequest, servletResponse);  
    }  
  
    @Override  
    public void destroy() {  
  
    }  
}  
 还有重要的一点是得导入两个包 。

	       <!-- 跨域 分享-->
<dependency>
    <groupId>com.thetransactioncompany</groupId>
    <artifactId>cors-filter</artifactId>
</dependency>
<dependency>
	<groupId>com.thetransactioncompany</groupId>
	<artifactId>java-property-utils</artifactId>
</dependency>

3种跨域 大家根据自己的需求进行选择。~~ 希望能帮到大家。

 如上有哪错误的欢迎各位大神提出。谢谢~~  




    于是在此相对,在这次开发中的跨域问题做个总结。



1.最开始用的是JSONP,JSONP大家应该也都比较熟悉,

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值