小编典典

毕加索使用HTTP发布加载图片

json

我的API具有针对每个HTTP请求的某种验证机制。端点之一具有使用HTTP post方法加载图像的功能。发布请求主体将包含一个从服务器端验证的JSON对象。

为此,我需要在http post请求正文中包含这样的JSON。

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

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


阅读 255

收藏
2020-07-27

共1个答案

小编典典

我从杰克逊·成加莱先生的暗示中得到了解决方案。

创建一个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客户端,添加此拦截器

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

使用此okhttp客户端创建Dowloader

OkHttpDownloader = downloader = new OkHttpDownloader(okHttpClient)

使用此下载器构建毕加索

Picasso picasso = new Picasso.Builder(context).downloader(downloader ).build();
2020-07-27