毕加索用HTTP帖子加载图片

时间:2016-02-02 10:47:20

标签: android json http-post picasso image-loading

我的API为每个HTTP请求都有一些验证机制。其中一个端点具有使用HTTP post方法加载图像的功能。 post请求体将包含一个JSON对象,该对象从服务器端进行验证。

为此我需要在http post请求体上包含这样的JSON。

{
    "session_id": "someId",
    "image_id": "some_id"
}

我如何用毕加索做到这一点?

1 个答案:

答案 0 :(得分:6)

我从Jackson Chengalai先生的提示中得到了解决方案。

创建一个Okhttp请求拦截器

http://example.com/index.php?roure=test/test&var=val

创建一个Okhttp客户端添加此拦截器

private static class PicassoInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {

        final MediaType JSON
                = MediaType.parse("application/json; charset=utf-8");
        Map<String, String> map = new HashMap<String, String>();
        map.put("session_id", session_id);
        map.put("image", image);
        String requestJsonBody = new Gson().toJson(map);
        RequestBody body = RequestBody.create(JSON, requestStringBody);
        final Request original = chain.request();
        final Request.Builder requestBuilder = original.newBuilder()
                .url(url)
                .post(body);
        return chain.proceed(requestBuilder.build());
    }
}

使用此okhttp客户端创建Dowloader

OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.interceptors().add(new PicassoInterceptor());

使用此下载程序构建Picasso

OkHttpDownloader = downloader = new OkHttpDownloader(okHttpClient)