ajax跨域post请求的java代理实现

来源:互联网 发布:php 环境变量path 编辑:程序博客网 时间:2024/06/11 21:00

文章来源http://blog.csdn.net/chunqiuwei/article/details/19924821


 最近开发的项目有个功能的需求如下:根据用户提供的外部链接(outter_url),在页面填写好查询条件(param)并向该url发起查询请求,查询返回的数据来动态生成html的table来显示数据,同时要求请求的方法是post请求。

在开发过程中用的是jquery的异步请求。问题出现了,网上搜了半天没有发现实现jquery跨域进行post请求的解决方案(貌似不支持),所以自己用java代码来发起post跨域请求

  关于实现思路的几点说明:

1)      项目中用的是spring,所以这个请求是在spring某个controller的方法中实现的,为了方便说明问题该方法假设为(ajaxProxy)

2)      在jsp页面中通过jquery的ajax方法,发起一个请求,该请求的url映射到1)中所说的那个ajaxProxy方法,并把查询条件(param)一起传递到ajaxProxy方法.部分代码如下

        

[javascript] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. $.ajax({  
  2.     type : "GET",  
  3.          //映射到controller对应方法的url  
  4.          url : "<c:url value='/user/put/queryItems'/>",  
  5.         //查询条件数据  
  6.         data : param,  
  7.     dataType : 'json',  
  8.     success : function(data) {//动态生成table,代码略}  


3)      在ajaxProxy方法中,用HttpURLConnection链接outter_url,并设置connection的请求方法为Post,并发送查询条件(param),该部分的代码实现如下:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. URL connect = new URL(outer_url);  
  2.   
  3. HttpURLConnection connection =(HttpURLConnection)connect.openConnection();  
  4.   
  5. Connection.setRequestMethod(“Post”);  
  6.   
  7. //发送查询条件  
  8.   
  9. OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());  
  10.   
  11. out.wirte(param);  
  12.   
  13. out.flush();  


4)      接收数据并返回数据,jsp页面中ajax的success方法处理接收到的数据data,并把data返回就可以了,接收数据的代码如下

       

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. StringBuffer data = new StringBuffer();  
  2. BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "gb2312"));  
  3. String line;              
  4. while ((line = reader.readLine()) != null) {          
  5.     data.append(line);            
  6. }  
  7.   
  8. return data;  

综上所述,实现跨域post请求的java实现代码如下

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. @RequestMapping("queryItems")  
  2. public @ResponseBody  
  3. String ajaxProxy(String name, String startTime, String endTime,  
  4.         String tag, Model m, HttpServletRequest req) throws UnsupportedEncodingException {  
  5.   
  6.         //拼接查询条件,组成json格式的数据发送    
  7.         JSONObject node = new JSONObject();         
  8.  try {    
  9.           
  10.       JSONObject param = new JSONObject();      
  11.        param.put("type""");    
  12.        param.put("typevalue""");    
  13.         //param.put("key", name);    
  14.         param.put("key"new String(name.toString().getBytes("utf-8"), "gbk"));  
  15.         param.put("start_time", startTime);    
  16.         param.put("end_time", endTime);    
  17.         param.put("tags", tag);    
  18.         node.put("param", param);    
  19.                                     
  20.         JSONObject user = new JSONObject();  
  21.         user.put("userid""123");  
  22.         node.put("user", user);  
  23.           
  24.         JSONObject device = new JSONObject();  
  25.         device.put("dnum""123");  
  26.         node.put("device", device);  
  27.           
  28.         JSONObject developer = new JSONObject();  
  29.         developer.put("apikey""******");  
  30.         developer.put("secretkey""*****");     
  31.         node.put("developer", developer);  
  32.          
  33.         node.put("action", action);  
  34.           
  35.     } catch (JSONException e1) {  
  36.         // TODO Auto-generated catch block  
  37.         e1.printStackTrace();  
  38.     }        
  39.       
  40.     // 使用POST方式向目的服务器发送请求  
  41.     URL connect;  
  42.     StringBuffer data = new StringBuffer();  
  43.     try {  
  44.         connect = new URL("outter_url");  
  45.         HttpURLConnection connection = (HttpURLConnection)connect.openConnection();  
  46.         connection.setRequestMethod("POST");  
  47.         connection.setDoOutput(true);  
  48.          
  49.         OutputStreamWriter paramout = new OutputStreamWriter(  
  50.                 connection.getOutputStream(),"UTF-8");  
  51.         paramout.write(json);  
  52.         paramout.flush();  
  53.   
  54.         BufferedReader reader = new BufferedReader(new InputStreamReader(  
  55.                 connection.getInputStream(), "gb2312"));  
  56.         String line;              
  57.         while ((line = reader.readLine()) != null) {          
  58.             data.append(line);            
  59.         }  
  60.       
  61.         paramout.close();  
  62.         reader.close();  
  63.     } catch (Exception e) {  
  64.         // TODO Auto-generated catch block  
  65.         e.printStackTrace();  
  66.     }  
  67.     return data.toString();  
  68.       
  69. }  

0 0
原创粉丝点击