$.ajax({ type : "GET",//映射到controller对应方法的url url : "<c:url value='/user/put/queryItems'/>",//查询条件数据 data : param,dataType : 'json',success : function(data) {//动态生成table,代码略}
@H_404_0@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();
@H_404_0@4)接收数据并返回数据,jsp页面中ajax的success方法处理接收到的数据data,并把data返回就可以了,接收数据的代码如下 @H_404_0@
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;@H_404_0@综上所述,实现跨域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(); }