zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

JAVA代理AJAX跨域 实现 请求 post
2023-09-11 14:19:05 时间

    最近开发的项目有个功能的需求如下:根据用户提供的外部链接(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方法.部分代码如下

        

$.ajax({
	type : "GET",
         //映射到controller对应方法的url
         url : "<c:url value='/user/put/queryItems'/>",
        //查询条件数据
        data : param,
	dataType : 'json',
	success : function(data) {//动态生成table,代码略}


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

URL connect = new URL(outer_url);

HttpURLConnection connection =(HttpURLConnection)connect.openConnection();

Connection.setRequestMethod(“Post”);

//发送查询条件

OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());

out.wirte(param);

out.flush();


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

       

StringBuffer data = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "gb2312"));
String line;			
while ((line = reader.readLine()) != null) {		
	data.append(line);			
}

return data;

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

	@RequestMapping("queryItems")
	public @ResponseBody
	String ajaxProxy(String name, String startTime, String endTime,
			String tag, Model m, HttpServletRequest req) throws UnsupportedEncodingException {
	
         //拼接查询条件,组成json格式的数据发送	
         JSONObject node = new JSONObject();       
	 try {	
			
		  JSONObject param = new JSONObject();    
		   param.put("type", "");  
		   param.put("typevalue", "");  
		    //param.put("key", name);  
		    param.put("key", new String(name.toString().getBytes("utf-8"), "gbk"));
		    param.put("start_time", startTime);  
		    param.put("end_time", endTime);  
		    param.put("tags", tag);  
		    node.put("param", param);  
					    	  		  
		    JSONObject user = new JSONObject();
		    user.put("userid", "123");
		    node.put("user", user);
		    
		    JSONObject device = new JSONObject();
		    device.put("dnum", "123");
		    node.put("device", device);
		    
		    JSONObject developer = new JSONObject();
		    developer.put("apikey", "******");
		    developer.put("secretkey", "*****");   
		    node.put("developer", developer);
		   
		    node.put("action", action);
		    
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}  	   
	    
		// 使用POST方式向目的服务器发送请求
		URL connect;
		StringBuffer data = new StringBuffer();
		try {
			connect = new URL("outter_url");
			HttpURLConnection connection = (HttpURLConnection)connect.openConnection();
			connection.setRequestMethod("POST");
			connection.setDoOutput(true);
	       
			OutputStreamWriter paramout = new OutputStreamWriter(
					connection.getOutputStream(),"UTF-8");
			paramout.write(json);
			paramout.flush();

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream(), "gb2312"));
			String line;			
			while ((line = reader.readLine()) != null) {		
				data.append(line);			
			}
		
			paramout.close();
			reader.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return data.toString();
		
	}