简体   繁体   中英

Unable to make CORS POST request in javascript to java web service(jersey)?

I am implementing Cross Resource Origin Sharing in Java Web services using Jersey.I created resource as followes:

@POST
    @Path("/getSubjects")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response getSubjects(TokenCheck tc) throws IOException, ServletException{ 
        String token = tc.getToken();
        String result = "";
        if(!token.equals("") && !token.equals(null)){
            context.getRequestDispatcher("/GetSubjectsWs?token="+token).include(request, response);
            String subs = request.getAttribute("subjects").toString();
            result = "{\"subjects\":\""+subs+"\"}";
        }else {
            result = "{\"subjects\":\"['Invalid Token login again']\"}";
        }
        JSONObject j = null;
        try {
            j = new JSONObject(result);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return Response.status(200).entity(j).header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Methods", "POST, GET, OPTIONS").header("Access-Control-Allow-Headers", "Content-Type:application/json").build(); 
    }

and making post request using javascript as :

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Client</title>
<script type="text/javascript">
function restReq() {
    var url = "http://localhost:8888/WebservicesServer/restful/getserver/getSubjects";
    var json = {
            "token":"8495C211F11C9B18E6651E03EB2995BC"
    };
    var client = new XMLHttpRequest();
    client.open("POST", url, true);
    client.setRequestHeader("Access-Control-Request-Methods", "POST");
    client.setRequestHeader("Content-Type", "application/json");
    client.send(json);
    client.onreadystatechange = function() {
        if (client.readyState == 4) {
           if ( client.status == 200) 
               console.log("success: " + client.responseText);
          else
              console.log("error: " +client.status+" "+ client.responseText);
       }
 };
}
</script>
</head>
<body>
<input type="button" value="getSubjects" onclick="restReq();">
</body>
</html>

When i clicked getSubjects Button in chrome I am getting error as : XMLHttpRequest cannot load ..localhost:8888/WebservicesServer/restful/getserver/getSubjects. Origin null is not allowed by Access-Control-Allow-Origin . But i am able to get response with GET request ,problem is with POST request my browser url file:///E:/Documents%20and%20Settings/Srinivas/Desktop/wars/JSClient2.html (File system) I tried in many ways like by setting origin etc, still unable to get json response (Server is Tomcat 7) please help to overcome this problem.

If you are using CORS then you should implement it as a filter rather than attempt to embed it in every method of every resource. Here's a simple example (you might want to tweak the settings to restrict it if that's of concern to you):

import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerResponse;
import com.sun.jersey.spi.container.ContainerResponseFilter;

/**
 * Filter to handle cross-origin resource sharing.
 */
public class CORSFilter implements ContainerResponseFilter
{
  private static final String ORIGINHEADER = "Origin";
  private static final String ACAOHEADER = "Access-Control-Allow-Origin";
  private static final String ACRHHEADER = "Access-Control-Request-Headers";
  private static final String ACAHHEADER = "Access-Control-Allow-Headers";

  public CORSFilter()
  {
  }

  @Override
  public ContainerResponse filter(final ContainerRequest request, final ContainerResponse response)
  {
    final String requestOrigin = request.getHeaderValue(ORIGINHEADER);
    response.getHttpHeaders().add(ACAOHEADER, requestOrigin);

    final String requestHeaders = request.getHeaderValue(ACRHHEADER);
    response.getHttpHeaders().add(ACAHHEADER, requestHeaders);
    return response;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM