java.net 解决ajax跨域访问问题

来源:互联网 发布:qq的smtp端口号 编辑:程序博客网 时间:2024/06/06 12:47

一、初遇问题 
业务系统A需要从我负责的网站首页中添加链接访问到他们的业务系统中,他给我提供了文档,文档中又他们系统的url,需要参数名及返回的json格式。想当然的就用ajax去请求,可是请求返回的json始终不对,而我把url放到浏览器却能打开显示正确json的网页。这时上网查,才发现ajax跨域访问需要用jsonp,所以开始用jsonp解决问题。 
二、问题没那么简单 
看网上方法修改请求方式,代码如下:

$.ajax({     url:url,     dataType:'jsonp',     processData: false,      type:'get',     success:function(data){       alert(data.msg);     },     error:function(XMLHttpRequest, textStatus, errorThrown) {       alert(XMLHttpRequest.status);       alert(XMLHttpRequest.readyState);       alert(textStatus);//可返回错误信息     }});   });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

可是请求的结果返回还是不对,上网搜发现原来jsonp的请求格式外包了一层callback,具体如下 
json格式:

{    "message":"获取成功",    "state":"1",    "result":{"name":"工作组1","id":1,"description":"11"}}
  • 1
  • 2
  • 3
  • 4
  • 5

jsonp格式:

callback({    "message":"获取成功",    "state":"1",    "result":{"name":"工作组1","id":1,"description":"11"}})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

这里我就遇到问题了,要继续使用jsonp格式,就必须要修改系统A接收接口,但显然这不可能,所以jsonp的方法在我这里不适用 
三、柳暗花明 
后来我突然想到,公司系统肯定不是第一次碰到跨域访问的问题,那他们是怎么解决的呢。我翻看代码,发现他们是在java后台中使用HttpURLConnection解决的,于是我效仿了一番,成功解决问题,下面是代码:

public String bigAnt(){        String url ="http://172.16.83.4:8000/custom/hangzhoushebao/bigant_start.php?op=bigant_start";        URL forWardUrl = null;        try {            forWardUrl = new URL(url);        } catch (MalformedURLException e) {            // TODO Auto-generated catch block            throw new BusinessException(String.format(                    "创建应用系统路径[%s]出错,错误消息:%s", url, e.getMessage()));            }        try {            HttpURLConnection conn = (HttpURLConnection) forWardUrl                    .openConnection();            conn.setConnectTimeout(3000);            conn.setRequestMethod("GET");            conn.setReadTimeout(3000);            conn.setRequestProperty("User-Agent",            "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");            conn.connect();            if(conn.getResponseCode()>300){                throw new BusinessException("连接失败");            }            BufferedReader reader = new BufferedReader(new InputStreamReader(                    conn.getInputStream(), "utf-8"));//这里解决乱码问题            String line = null;            StringBuffer buffer = new StringBuffer(conn.getContentLength());            while ((line = reader.readLine()) != null) {                buffer.append(line);            }            JSONObject rstJson = JSONObject.fromObject(buffer.toString());            //返回0代表失败,msg中保存的是错误信息            if("0".equals(rstJson.getString("status"))){                throw new BusinessException(rstJson.getString("msg"));            }            else{            //返回成功时向前台传数据                   String json = String.format("{success:true,\"result\":[{\"url\":\"%s\"}]}",rstJson.getString("msg"));                System.out.println(json);                super.createJSonData(json);            }            }catch (IOException e) {                throw new BusinessException(e.getMessage());            }        return AJAX;    }