【问题标题】:How do I send JSon as BODY In a POST request to server from an Android application?如何在从 Android 应用程序到服务器的 POST 请求中将 JSon 作为 BODY 发送?
【发布时间】:2010-09-28 17:41:20
【问题描述】:

我正在开发我的第一个 Android 应用程序。我想要做的是对 REST 服务的 POST 请求,我希望这个请求的 BODY 是 JSON 字符串。

我正在使用 google 的 GSON 生成发送到服务器的 JSON。这是执行 POST 请求的代码:

HttpPost requisicao = new HttpPost();
requisicao.setURI(new URI(uri));
requisicao.setHeader("User-Agent", sUserAgent);
requisicao.setHeader("Content-type", "application/json");
HttpResponse resposta = null;
//I can see the json correctly print on log with the following entry.
Log.d(TAG, "JSon String to send as body in this request ==>> " + jsonString);
//than I try to send JSon using setEntityMethod
StringEntity sEntity = new StringEntity(jsonString, "UTF-8");
requisicao.setEntity(sEntity);

resposta = httpClient.execute(requisicao);
resultado = HttpProxy.leRespostaServidor(resposta);

响应代码是 400 BAD REQUEST,我可以从服务器日志中读取信息。它说身体没有正确发送:

13:48:22,524 ERROR [SynchronousDispatcher] Failed executing POST /peso/cadastrar/maia.marcos@gmail.com
org.jboss.resteasy.spi.BadRequestException: Could not find message body reader for type: class java.io.Reader of content type: application/json

服务器端的代码是一个简单的Seam Rest Service:

    @POST
 @Path("/cadastrar/{userEmail}")
 @Consumes(MediaType.APPLICATION_JSON)
 public String cadastraPeso(@PathParam("userEmail") String email, Reader jsonString)
 {
  LineNumberReader lnr = new LineNumberReader(jsonString);
  try {
   String json = lnr.readLine();
   if(json != null)
   {
    log.debug("String json recebida do device ==>> " + json);
   } 
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
   return "OK - o e-mail processado foi ==>> " + email;
 }

Android 客户端代码可能有什么问题?我研究了网络,并没有找到任何关于这个错误的真正有用的信息。

[]s

【问题讨论】:

    标签: android json rest post seam


    【解决方案1】:

    抱歉,刚刚发现错误出在 Rest 服务上。我已经对其进行了更改,现在它接收了一个 String 而不是 Reader 对象,并且它按预期工作,服务器端的 REST 端点代码现在是:

    @POST
    @Path("/cadastrar/{userEmail}")
    @Consumes(MediaType.APPLICATION_JSON)
    public String cadastraPeso(@PathParam("userEmail") String email, String jsonString)
    {
            String json = jsonString;
            if(json != null)
            {
                log.debug("String json received from device ==>> " + json);
            }   
            return "OK - processed email ==>> " + email;
    }
    

    并且在服务器端正确接收到 JSON 字符串。

    所以上面的 Android 代码按预期工作。

    【讨论】:

    • 嗨亚瑟,我不得不告诉你,我仍然有点迷失使用堆栈溢出。作为初学者,它看起来对我来说信息太多,我的意思是,关于这一点的所有力学,cmets,帖子,因为第一印象看起来有点混淆这些论坛,但我发现使用它的信息很好,所以我希望能习惯快。
    • 很高兴您发现此网站很有用,但请通过单击向下箭头下方的图标接受您自己的答案作为已接受的答案。当鼠标悬停在它上面时,它会以绿色突出显示。
    • @Shervin 看来我必须等几天才能做到这一点。我会做的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多