【问题标题】:Picasso load image with HTTP postPicasso 使用 HTTP post 加载图像
【发布时间】:2016-02-02 10:47:20
【问题描述】:

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

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

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

我怎样才能用毕加索做到这一点?

【问题讨论】:

  • 你想下载带标题的图片吗?
  • 不,我想知道如何使用毕加索发送帖子请求。
  • 您可以使用 picasso 中的自定义下载器自定义您的请求。 Picasso 使用 okhttpclient 作为下载器。stackoverflow.com/questions/33455084/…
  • 感谢Jackson Chengalai 先生。它有效。

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


【解决方案1】:

我从Mr.Jackson Chengalai给出的提示中得到了解决方案。

创建一个 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 picasso = new Picasso.Builder(context).downloader(downloader ).build(); 

【讨论】:

  • 这适用于毕加索的哪个/多个版本?
  • 毕加索:2.5.2 和 okhttp:2.7.2
  • 我们可以在Picasso.load(url)中添加图片的url。如何添加帖子正文参数?
  • @amasiddawadeyar 请参考我回答的“拦截”方法中的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-14
  • 2019-06-27
  • 1970-01-01
  • 1970-01-01
  • 2021-07-18
  • 2017-05-13
  • 2019-08-20
相关资源
最近更新 更多