ajax call to jax-rs with jquery issue

两盒软妹~` 提交于 2020-01-02 10:25:11

问题


I'm trying to call a Webservice that consumes a json object with post method .I did it then It wont work again don't know what is the problem.
here is my method

@POST
@Path("/post")
@Consumes("application/json")
@Produces("application/json")
public Response testClient(Client c) throws IOException {
    System.out.println(c.getAdresseCl());
    ResponseBuilder builder = Response.ok(c.getAdresseCl());
    builder.header("Access-Control-Allow-Origin", "*");
    builder.header("Access-Control-Max-Age", "3600");
    builder.header("Access-Control-Allow-Methods", "*");
    builder.header(
            "Access-Control-Allow-Headers",
            "X-Requested-With,Host,User-Agent,Accept,Accept-Language,Accept-Encoding,Accept-Charset,Keep-Alive,Connection,Referer,Origin");
    return builder.build();
}

to call this I used this

$.ajax({
  type: 'POST',
  url: "http://localhost:9080/FournisseurWeb/jaxrs/clients/post",
  data: '{"adresseCl":"tunis"}',
  dataType:'json',
  contentType: "application/json; charset=utf-8", 
  success: function (msg) {
    alert(msg);
  },

  error: function (xhr, ajaxOptions, thrownError) {
    alert('error');
  }

});

well I remark that when I set the contentType to application/json the method changes to OPTIONS . and when I don't use the content type I got "415 Unsupported Media Type " I dont know how to fix this. I passed too much time without results :(
thank you for helping me


回答1:


When attempting to make cross-domain AJAX requests in certain browsers, it is a common to see the HTTP Method change to OPTIONS in lieu of a more meaningful error message.

I noticed in your URL that you're including the protocol, domain, and port, which supports the theory that you're actually trying to make an AJAX request to a different domain/port combination than the originating context.

To clarify, even if your request is originating from localhost and targeting localhost, the ports (9080) and protocols (http) must also match.

Thus, if the page you loaded is "http://localhost:8080" and you're trying to make an AJAX request to "http://localhost:9080", the request will fail, may throw same-domain security errors, 415 Unsupported Media Type, and/or change the HTTP Method to OPTIONS.

One way to make sure you avoid this mistake is to only use full or relative paths when making AJAX requests, such as:

url: "/FournisseurWeb/jaxrs/clients/post",

This forces you to always make requests to the same domain.

Cross-domain Requests

If you do indeed require the ability to make cross-domain requests, this is possible, but only through two methods.

First, you can use a proxy, where you make an HTTP request to your domain and then forward the request onto another server. Servers need not be concerned with same-domain policies when sending and receiving data from one another.

Second, you can use JSONP, also known as script tag remoting, which involves exploiting the <script> element's ability to send requests across different domains.

// added callback= query parameter to convert this to JSONP
$.ajax({
  type: 'POST',
  url: "http://localhost:9080/FournisseurWeb/jaxrs/clients/post?callback=",
  data: '{"adresseCl":"tunis"}',
  dataType:'json',
  contentType: "application/json; charset=utf-8", 
  success: function (msg) {
    alert(msg);
  },    
  error: function (xhr, ajaxOptions, thrownError) {
    alert('error');
  }
});

NOTE: When using JSONP, your server must respond with the JSON wrapped up in a function call identified by the callback parameter. See the jQuery documentation for more in-depth details .

Other than that, you must make AJAX requests to the same domain the page was loaded from.




回答2:


this is the method that consumes a text xml fomat and map it to an object to persist it next

@POST
@Path("/inscription")
@Produces(MediaType.TEXT_HTML)
public Response testClient(String s) {
    ResponseBuilder builder = null;

    try {

        final String xmlString = s;
        final StringReader xmlReader = new StringReader(xmlString);
        final StreamSource xmlSource = new StreamSource(xmlReader);
        final JAXBContext jaxbContext = JAXBContext
                .newInstance(Client.class);
        final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        final Client client = (Client) unmarshaller.unmarshal(xmlSource,
                Client.class).getValue();
        System.out.println("nomCl  : " + client.getNomCl());
        System.out.println("prenomCl  : " + client.getPrenomCl());
        System.out.println("emailCl  : " + client.getEmailCl());
        System.out.println("numTel  : " + client.getNumTel());
        System.out.println("long_  : " + client.getLong_());
        System.out.println("lat  : " + client.getLat());
        System.out.println("LoginCl  : " + client.getLoginCl());
        System.out.println("PasswordCl  : " + client.getPasswordCl());
        System.out.println("adresseCl  : " + client.getAdresseCl());
        EntityManagerFactory factory;
        factory = Persistence.createEntityManagerFactory("FournisseurWeb");
        EntityManager em = factory.createEntityManager();
        em.getTransaction().begin();
        em.persist(client);
        em.getTransaction().commit();
        em.close();
        factory.close();
        builder = Response.ok("true");
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
        builder = Response.ok("false");
        builder.header("Access-Control-Allow-Origin", "*");
        builder.header("Access-Control-Max-Age", "3600");
        builder.header("Access-Control-Allow-Methods", "POST");
        builder.header(
                "Access-Control-Allow-Headers",
                "X-Requested-With,Host,User-Agent,Accept,Accept-Language,Accept-Encoding,Accept-Charset,Keep-Alive,Connection,Referer,Origin");
        return builder.build();
    }
    builder.header("Access-Control-Allow-Origin", "*");
    builder.header("Access-Control-Max-Age", "3600");
    builder.header("Access-Control-Allow-Methods", "POST");
    builder.header(
            "Access-Control-Allow-Headers",
            "X-Requested-With,Host,User-Agent,Accept,Accept-Language,Accept-Encoding,Accept-Charset,Keep-Alive,Connection,Referer,Origin");
    return builder.build();
}

I use to call this method using ajax with this sample :

var x="<client><nomCl>Taarit</nomCl><prenomCl>Aymen</prenomCl><emailCl>aymen.taarit@gmail.com</emailCl><numTel>222</numTel><long_>1.66</long_></client>";
$.ajax({
        url: 'http://localhost:9080/FournisseurWeb/jaxrs/clients/cl',
        type: 'post',
        scriptCharset: "utf-8" ,
        dataType:"xml",
        data: x,
        success: function(data, status) {  
        console.log(data);         
        }
    });

this is a jax-rs call with ajax POST using cross domain so hope that it helps :)

NOTE: The cross-domain call without JSONP is legal here because the server is returning the following header, which enables cross-domain AJAX!

 builder.header("Access-Control-Allow-Origin", "*");

See Mozilla Developer Center page on Access-Control-Allow-Origin for more details.



来源:https://stackoverflow.com/questions/10679060/ajax-call-to-jax-rs-with-jquery-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!