代码之家  ›  专栏  ›  技术社区  ›  groo

如何将JSon作为POST请求的主体从Android应用程序发送到服务器?

  •  13
  • groo  · 技术社区  · 15 年前

    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坏请求,我可以从服务器日志中读取信息。上面写着尸体没有被正确送到:

    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;
     }
    

    []秒

    1 回复  |  直到 8 年前
        1
  •  11
  •   groo    8 年前

    抱歉,伙计们,结果是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字符串。

    所以上面的de-Android代码工作正常。

    推荐文章