java解决跨域访问。

直接使用第一种方法,需要自己构建参数。

参考 


Ajax JSON页面上直接跨域访问会遇到诸多问题:无法正常访问以及无法正常获取返回值等

可通过Ajax方式呼叫后台程式,交由java.net去呼叫跨域地址,解决此问题

以下為部分程式:

import java.net.URL;
import java.net.URLConnection;

 

static String url = "http://api.xxx.xxx.com/xxx/xxx?xxx=xx&xxx=xxx";

public String sendShortMessage(String smsSrc, String mobileNo) {

String line = "";
  StringBuffer sb = new StringBuffer();
  
  try {
   
   URL u = new URL(url);
   URLConnection uc = u.openConnection();
   
   uc.setDoOutput(true);
   
   BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
   
   while ((line = in.readLine()) != null) {
    
    sb.append(line);


    System.err.println("readLine: " + sb.toString());

    // 此处获得即为跨域访问的返回值,这次测试获取的是JSON格式的字串
   }
  
   in.close();
  }
  catch (Exception e) {
   
   e.printStackTrace();
  }
  
  return new String(sb);
 }


java 服务端解决ajax跨域问题

//过滤器方式 可以更改为拦截器方式
public class SimpleCORSFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; 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"); chain.doFilter(req, res); } public void init(FilterConfig filterConfig) {} public void destroy() {} }
posted @ 2017-02-10 11:19  thewindkee  阅读(282)  评论(0编辑  收藏  举报