我正在开发我的第一个 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/