簡體   English   中英

Android HttpPost to Jersey Web服務返回404

[英]Android HttpPost to Jersey web service returns 404

我正在嘗試在我的Android應用程序中發布資源。 GET可以正常工作。 在我的android代碼段的末尾執行response.getStatusLine().getStatusCode()時,另一側的POST返回404(請參見下文)

我的Jersey網絡服務方法如下所示:

@POST
@Path("/create")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response create(@FormParam("name") String name,
        @FormParam("description") String description) throws IOException {

    User user = new User();
    user.setName(name);
    user.setDescription(description);
    // store object in database...
    return Response.status(Status.OK).build();
}

以及android應用中的代碼:

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("**my-url**/create");
ArrayList<NameValuePair> paramspost = new ArrayList<NameValuePair>();
paramspost.add(new BasicNameValuePair("name", "My name"));
paramspost.add(new BasicNameValuePair("description", "My description"));
    try {
        httpPost.setHeader("Content-Type",
            "application/x-www-form-urlencoded;charset=UTF-8");

        httpPost.setEntity(new UrlEncodedFormEntity(paramspost, "UTF-8"));
        HttpResponse response = httpClient.execute(httpPost);

        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

最后的狀態碼是404,我的數據庫中什么也沒有存儲。 我的代碼有什么問題?

據我所知,您從未定義請求方法。

httpPost.setRequestMethod("POST");

這應該可以解決您的問題。

在您的請求中,您指定了Content-Type:“ application / x-www-form-urlencoded; charset = UTF-8”,但是在您的資源中,您使用的是“ MediaType.APPLICATION_FORM_URLENCODED”,我相信沒有charset擴展名。 這可能會引起麻煩,因此沒有找到可以消耗您的請求的資源。 嘗試從請求標頭中省略charset屬性。

Content-Type中的jersey和charset屬性也存在問題。 在這里看看

原來,我的更改未正確部署到Tomcat 我從Tomcat文件夾中刪除了所有內容,然后再次部署了(通過eclipse創建戰爭似乎並不總是正確地取消部署)。

這意味着我的問題中呈現的代碼可以像這樣正常工作。 而且我發現刪除指定的內容類型沒有任何區別。

暫無
暫無

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

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