简体   繁体   中英

Ajax request everytime passing through error (not answering in JSONP in server-side jersey/java restful WS?)

I have an API made with Jersey (restful web service), very simple. I have been able to make request/answers through my android application.

Now I'm developing a web backend in order to manage data. The thing is that when I make calls with ajax, everytime the answer is passing through the "error" part.

Strange as it may seem, giving a glance to firebug the call/answer seem to be correctly made, with the final 200 OK answer and the right JSON data.

The javascript code is the following:

$(document).ready(function (){

        var theUrl = "***url****/Rest/provincias";
        jQuery.ajax({
            beforeSend: function(req) {
                req.setRequestHeader("Accept", "application/json");
            },
            cache: false,
            async: false,
            crossDomain: true,
            type: "GET",
            url: theUrl,
            dataType: "jsonp",
            jsonp: false,
            contentType: "application/json; charset=utf-8",
            statusCode: {
                200: function (data){
                    //OK ANSWER
                    alert("Answer OK: " + data.response);
                }
            },

            error: function (xhr,err) {
                alert("Otra vez en error... " + xhr + "' '" + err);
            },
            success: function (data){
                //Comprobamos en el json si tenemos true o false.

                alert("éxito!! " + data);
            },
            complete: function (xhr, status) {

                if (status === 'error' || !xhr.responseText) {
                    alert("errorrr");
                }
                else {
                    var data = xhr.responseText;
                    alert("Info en complete: " + data);
                }
            }
        });


    });

The JSON text written when I make the call through the browser is similar to this:

{
  "response": true,
  "data_int": 0,
  "data_boolean": false,
  "data_float": 0.0,
  "data_double": 0.0,
  "data_byte": 0,
  "data_short": 0,
  "data_long": 0,
  "data_char": "\u0000",
  "object": [
  {
  "id": 1,
  "nombreCas": "Ãlava",
  "nombreEus": "Araba",
  "localizacion": {
    "id": 46,
    "latitude": "42.847511",
    "longitude": "-2.679730"
  },
  "pueblos": {
    "1": {
      "id": 1,
      "nombreCas": "Alegría",
      "nombreEus": "Dulantzi",
      "provincia": null,
      "localizacion": {
        "id": 1,
        "latitude": "42.841171",
        "longitude": "-2.512608"
      },
      "barrios": {}
    },

........

As I have been able to read, the error could be because the answer is not in JSONP format (restful WS is answering with a JSON format text), so the line dataType: "jsonp" can't be deleted. If I delete it, the answer is not made correctly.

Is there something to add to my web service? For example, how to add JSONP support in this code:

package main.java.webService;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import main.java.model.AccessManager;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import main.java.dto.Provincia;
import main.java.dto.ReturningClass;

/**
 * @author Jon_Inazio
 *
 */
@Path("provincias")
public class PueblosProvinciasService {

    @GET
    @Produces("application/json")
    public String getProvincias(){
        String provincias = null;
    HashMap<Integer, Provincia> provinciasList = new HashMap<Integer,     Provincia>();
        try{
        provinciasList = new AccessManager().getProvincias();
                GsonBuilder gb = new     GsonBuilder().serializeNulls().setPrettyPrinting(); 
            Gson gson = gb.create();
            Collection<Provincia> arrayProvs = new ArrayList<Provincia>();
        arrayProvs = provinciasList.values();
            /*
             * CONVERTIR HASH MAP A UNA LISTA --> JSON LO PIDE ASI
         */
            //ReturningClass<HashMap<Integer, Provincia>> ret = new     ReturningClass<HashMap<Integer, Provincia>>(true, provinciasList);
            ReturningClass<Collection<Provincia>> ret = new     ReturningClass<Collection<Provincia>>(true, arrayProvs);
            System.out.println("**Se han consultado las provincias!!");
            provincias = gson.toJson(ret);
        }catch(Exception e){
            e.printStackTrace();
    }

        return provincias;
}

}

Thanks in advance and I hope everyone can understand me :).

When I write Jersey Web Services I typically have my methods return Response objects. This allows me to include information about the status code and response headers. This is especially important when making cross domain requests (like it seems you are doing) because it allows you to specify the important response header "Access-Control-Allow-Origin" which enables cross domain requests.

@GET
@Produces("application/json")
@Path("myPath")
public Response getAllCommissions() {

    // Perform method function
    String json = "OUTPUT_OF_METHOD";

    // Creates a ResponseBuilder
    ResponseBuilder builder = new ResponseBuilderImpl();
    // Sets the header of the return data
    builder.header("content-type", "application/json");
    // Sets the response code as a 200
    builder.status(Response.Status.OK);
    // Allows Cross Domain Requests from any origin
    builder.header("Access-Control-Allow-Origin", "*");
    // Adds your result data to the Response
    builder.entity(json);
    // Creates the Response
    return builder.build();
}

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