android - 如何在 POST 请求中将 JSON 作为 BODY 从 Android 应用程序发送到服务器?

标签 android json rest post seam

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

我正在使用谷歌的 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 服务:

    @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

最佳答案

抱歉各位,刚刚发现错误出在 Rest 服务上。我已经更改了它,现在它接收到一个字符串而不是 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 代码按预期工作。

关于android - 如何在 POST 请求中将 JSON 作为 BODY 从 Android 应用程序发送到服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3815522/

相关文章:

android - 找不到与给定名称匹配的资源(位于 'theme' ,值为 '@android:style/Theme.my_theme' )。(APT0000)

javascript - 循环遍历数组中的 json 响应

c# - 将查询字符串添加到 REST GET

Android:当用户在浏览器中单击“共享”时,我希望我的应用位于 'Share via' 列表中

android - adb 卸载失败 失败 [DE​​LETE_FAILED_OWNER_BLOCKED]

android - 使用 facebook graph api 获取 friend 生日 v2.0

javascript - 如何捕获 JSON 导出并发送到 URL

database - 查询谷歌电子表格的特定工作表

javascript - 在 Spotify API 中授权期间获取 HTTP 415 不支持的媒体类型

python - JIRA-Python 的基本身份验证不再适用于 REST API 调用。接下来是什么?