簡體   English   中英

嘗試使用jquery ajax和jersey作為json POST到RESTful Web服務

[英]Trying to POST as a json to a RESTful web service using jquery ajax and jersey

我做了一個RESTful網絡服務。

@POST
@Path("/test")
@Consumes({ MediaType.APPLICATION_JSON})
public String test(TestObject to)
{
    System.out.println(to.getTestString());
    return "SUCCESS";
}

我有使用@XmlRootElement創建的對象

@XmlRootElement
public class TestObject implements Serializable {
    private static final long serialVersionUID = 1L;

    private String testString;

    public TestObject() {}

    public TestObject(String testString) {
        this.testString = testString;
    }

    public String getTestString() {
        return testString;
    }
    public void setTestString(String testString) {
        this.testString = testString;
    }
}

然后我嘗試使用以下ajax調用來調用它

$.ajax({
    url: 'http://localhost:8080/testPage/test/',
    type: 'POST',
    data: '{"testString":"test"}',
    dataType: 'text',
    contentType: "application/json; charset=utf-8",
    success: function(jqXHR, textStatus, errorThrown){
        alert('Success');
    },
    error: function(jqXHR, textStatus, errorThrown){
        alert("jqXHR - " + jqXHR.statusText + "\n" + 
              "textStatus - " + textStatus + "\n" + 
              "errorThrown - " + errorThrown);
    }
});

我最終得到了textStatus的'錯誤'。 它似乎甚至沒有達到我的測試服務。 當我只傳遞text / plain時,我將獲得GET工作甚至POST工作。 當我試圖傳遞一個json時,我無法讓它工作。

使用海報 Firefox的附加組件我能夠成功調用傳遞相同數據的服務。 我添加了一些額外的日志記錄來捕獲服務端的請求標頭,所以它似乎至少看到了請求,但它沒有做任何事情。

以下是我從日志中獲得的請求。 最重要的一個是失敗的ajax。 最底層的是用POSTER成功的那個。 (不是真正的代碼,但我沒有看到任何更好的代碼)

INFO: 1 * Server in-bound request
1 > OPTIONS http://localhost:8080/testPage/test 
1 > Host: localhost:8080
1 > User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:13.0) Gecko/20100101 Firefox/13.0.1
1 > Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
1 > Accept-Language: en-us,en;q=0.5
1 > Accept-Encoding: gzip, deflate
1 > DNT: 1
1 > Connection: keep-alive
1 > Origin: http://localhost:8081
1 > Access-Control-Request-Method: POST
1 > Access-Control-Request-Headers: content-type
1 > Pragma: no-cache
1 > Cache-Control: no-cache
1 > 

INFO: 2 * Server in-bound request
2 > POST http://localhost:8080/testPage/test
2 > Host: localhost:8080
2 > User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:13.0) Gecko/20100101 Firefox/13.0.1
2 > Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
2 > Accept-Language: en-us,en;q=0.5
2 > Accept-Encoding: gzip, deflate
2 > DNT: 1
2 > Connection: keep-alive
2 > Content-Type: application/json; charset=utf-8
2 > Content-Length: 22
2 > Cookie: JSESSIONID=bvizai6k0277
2 > Pragma: no-cache
2 > Cache-Control: no-cache
2 >
{"testString": "test"}

從這似乎是沒有讓json傳遞給服務。 我已經嘗試過如上所述寫出json,我嘗試使用JSON.stringify創建它並沒有成功。

當嘗試在jquery ajax調用中使用POST將json發送到RESTful Web服務時,有誰知道我做錯了什么?

你在ajax調用中嘗試過dataType: 'json'而不是dataType: 'text'嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM