【问题标题】:Android HttpPost to Jersey web service returns 404Android HttpPost 到 Jersey 网络服务返回 404
【发布时间】:2014-11-01 20:14:18
【问题描述】:

我正在尝试在我的 Android 应用中发布资源。 GET 工作没有任何问题。 POST 在我的 android sn-p 末尾执行 response.getStatusLine().getStatusCode() 时返回 404(见下文)

我的 Jersey Web 服务方法如下所示:

@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 app中的代码:

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,我的数据库中没有存储任何内容。我的代码有什么问题?

【问题讨论】:

  • 你试过重启你的网络服务吗?
  • 嗯,等等。您实际上在哪里将“POST”定义为 HTML 请求方法?

标签: java android jersey http-post jax-rs


【解决方案1】:

据我所知,您从未定义过请求方法。

httpPost.setRequestMethod("POST");

这应该可以解决您的问题。

【讨论】:

  • HttpPost 类型的方法 setRequestMethod(String) 未定义。我正在尝试与此处相同:androidsnippets.com/…
  • 哦等等这不是HttpConnection也许你试试这个?
【解决方案2】:

在您的请求中,您指定了 Content-Type:“application/x-www-form-urlencoded;charset=UTF-8”,但是在您的资源中,您使用了“MediaType.APPLICATION_FORM_URLENCODED”,我相信没有字符集扩展。这可能会引起麻烦,因此没有找到可以消耗您的请求的资源。尝试从请求标头中省略 charset 属性。

Content-Type 中的 jersey 和 charset 属性也存在问题。看看here

【讨论】:

    【解决方案3】:

    原来我的更改没有正确部署到Tomcat。我从我的Tomcat 文件夹中删除了所有内容并再次部署(看起来通过 eclipse 创建战争并不总是正确地取消部署)。

    这意味着我的问题中提供的代码可以像这样正常工作。而且我发现删除指定的内容类型没有任何区别。

    【讨论】:

      猜你喜欢
      • 2013-11-19
      • 1970-01-01
      • 2018-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-06
      • 2019-05-02
      • 1970-01-01
      相关资源
      最近更新 更多