• 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() {} }
  • 相关阅读:
    数学基础
    Codeforces Beta Round 84 (Div. 2 Only)
    Codeforces Round 256 (Div. 2)
    Codeforces Round FF(Div. 2)
    Codeforces Round 254 (Div. 2)
    Python3 集合(无序的set)
    Python3 字典(map)
    Python3 元组
    Python3 列表
    初等数论及其应用——唯一分解定理
  • 原文地址:https://www.cnblogs.com/thewindkee/p/12873243.html
Copyright © 2020-2023  润新知