android - 使用 robospice google http 客户端在 Post 中发送 JSON

标签 android json post robospice google-http-client

我在使用 Robospice google http java 客户端创建发布请求和发送 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 转换为字节数组并将其包含在您的发布请求中。

关于android - 使用 robospice google http 客户端在 Post 中发送 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20143040/

相关文章:

android - Gradle 3.0 transformClassesWithStackFramesFixerForDebug 重复条目

android - 没有用 ArrayList 填充 ListView

java - 在 Android 上使用自定义异常词匹配进行语音转文本

php - 从 PHP 表单发布到 mySQL 中的多行

php - HTML 登录表单连接到数据库

android - 在 Unity Android 中使用 assetbundle 和流媒体资源文件夹

java - 从 json 中转义 "["括号

java - 使用 GSON 将多个 Collection<String> 合并为一个 JSON String

c# - 自定义 JsonConverter WriteJson 不会改变子属性的序列化

Android 和 RESTful 服务