我在使用Robospice-google-http-java客户端创建post请求和发送json时遇到问题。我的问题是,服务器接收到一个空的请求数据。(postData中没有任何内容)
@Override
public AjaxResult loadDataFromNetwork() throws Exception {
JsonHttpContent jsonHttpContent = new JsonHttpContent(new JacksonFactory(), jsonObject);
//ByteArrayContent.fromString("application/json", jsonObject.toString())
HttpRequest request = getHttpRequestFactory().buildPostRequest(
new GenericUrl(baseUrl),
jsonHttpContent);
request.getHeaders().setContentType("application/json");
request.setParser(new JacksonFactory().createJsonObjectParser());
request.setContent(jsonHttpContent);
HttpResponse httpResponse = request.execute();
AjaxResult result = httpResponse.parseAs(getResultType());
return result;
}
提前感谢!
您可以这样做:
public class SignIn_Request extends GoogleHttpClientSpiceRequest<Login> {
private String apiUrl;
private JSONObject mJsonObject;
public SignIn_Request(JSONObject mJsonObject) {
super(Login.class);
this.apiUrl = AppConstants.GLOBAL_API_BASE_ADDRESS + AppConstants.API_SIGN_IN;
this.mJsonObject = mJsonObject;
}
@Override
public Login loadDataFromNetwork() throws IOException {
Ln.d("Call web service " + apiUrl);
HttpRequest request = getHttpRequestFactory()//
.buildPostRequest(new GenericUrl(apiUrl), ByteArrayContent.fromString("application/json", mJsonObject.toString()));
request.setParser(new JacksonFactory().createJsonObjectParser());
return request.execute().parseAs(getResultType());
}
}
将JSON转换为字节数组,并将其包含在您的post请求中。
我自己一直在寻找类似的解决方案,我找到了谷歌希望您如何格式化内容的合理解释。
我制作了POJO类,只添加了一些getter和setter,并将其用于数据,这似乎对我有效
google http java客户端json更新现有对象