【问题标题】:how to add Cross Origin Resource Sharing in my java fie如何在我的 java 文件中添加跨域资源共享
【发布时间】:2017-10-30 12:42:26
【问题描述】:

我写的不正确

HttpClient httpClient = HttpClientBuilder.create().header("Access-Control-Allow-Origin", "*")
                .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
                .allow("OPTIONS").build();

【问题讨论】:

    标签: java restful-authentication


    【解决方案1】:

    您可以为 CORS 源过滤器编写组件类

     @Component
    public class CorsFilterConfiguration 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, PUT, PATCH, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type, authToken"); //TODO: Fix 'token' to 'OAuth' / 'SAML' header.
            chain.doFilter(req, res);
        }
        public void init(FilterConfig filterConfig) {
        }
        public void destroy() {
        }
    }
    

    【讨论】:

    • 但我没有实现 servlet。我正在使用一个主要功能来生成安静的 Web 服务。有什么方法可以在不使用servelt过滤器的情况下做到这一点??
    • 您可以在响应中设置这些也可以返回 Response.ok() .header("Access-Control-Allow-Origin", "*") .header("Access-Control-Allow-Methods ", "POST, GET, PUT, UPDATE, OPTIONS") .header("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With").build();
    • 这是我的代码。我该怎么做请帮忙
    • public static void main(String[] args){HttpClient httpclient = HttpClientBuilder.create().build();String loginURL =; HttpPost httpPost = new HttpPost(loginURL); HttpResponse 响应 = null;响应 = httpclient.execute(httpPost);最终 int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { System.out.println("对 Force.com 进行身份验证时出错:"+statusCode); } 字符串 getResult = null; getResult = EntityUtils.toString(response.getEntity()); ioException.printStackTrace(); } httpPost.releaseConnection(); }
    • 是的。我正在制作安静的 web 服务,以便在 clintside 有角度的 js 应用程序可以使用它
    猜你喜欢
    • 2011-05-07
    • 2013-01-12
    • 2018-05-04
    • 2011-07-31
    • 2019-02-25
    • 2011-07-05
    • 2019-07-13
    • 2018-05-14
    • 1970-01-01
    相关资源
    最近更新 更多