小编典典

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

json

我正在开发我的第一个Android应用程序。我正在尝试做的是对REST服务的POST请求,我希望此请求的主体为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客户端代码可能有什么问题?我已经研究了网络,但没有发现有关此错误的任何真正有用的信息。

[]秒


阅读 769

收藏
2020-07-27

共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字符串已在服务器端正确接收。

因此,上面的de Android代码按预期工作。

2020-07-27