-1

I have written this it's not correct

HttpClient httpClient = HttpClientBuilder.create().header("Access-Control-Allow-Origin", "*")
                .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
                .allow("OPTIONS").build();
Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62
Vijay
  • 93
  • 1
  • 8

1 Answers1

1

You can write component class for CORS origin filter

 @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() {
    }
}
Satish Kr
  • 590
  • 5
  • 12
  • but i am not implementing servlet .I am using a main function where i am producing restful web-services. Is there any way to make it without using servelt filters ?? – Vijay May 30 '17 at 07:23
  • You can set these in your response also return 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(); – Satish Kr May 30 '17 at 09:56
  • This is the my code . how would i do this please help – Vijay May 30 '17 at 10:05
  • public static void main(String[] args){HttpClient httpclient = HttpClientBuilder.create().build();String loginURL =; HttpPost httpPost = new HttpPost(loginURL); HttpResponse response = null; response = httpclient.execute(httpPost); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { System.out.println("Error authenticating to Force.com: "+statusCode); } String getResult = null; getResult = EntityUtils.toString(response.getEntity()); ioException.printStackTrace(); } httpPost.releaseConnection(); } – Vijay May 30 '17 at 10:09
  • yes . i was producing restful webservices so that at clintside an angular js application can consume it – Vijay May 30 '17 at 10:51