我的API对每个HTTP请求都有一些验证机制。其中一个端点具有使用HTTP POST方法加载图像的功能。POST请求正文将包含一个JSON对象,该对象从服务器端进行验证。
为此,我需要在HTTP POST请求正文中包含类似于此的JSON。
{
"session_id": "someId",
"image_id": "some_id"
}
我该如何使用Picasso实现这个功能?
我的API对每个HTTP请求都有一些验证机制。其中一个端点具有使用HTTP POST方法加载图像的功能。POST请求正文将包含一个JSON对象,该对象从服务器端进行验证。
为此,我需要在HTTP POST请求正文中包含类似于此的JSON。
{
"session_id": "someId",
"image_id": "some_id"
}
我从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());
}
}
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.interceptors().add(new PicassoInterceptor());
OkHttpDownloader = downloader = new OkHttpDownloader(okHttpClient)
Picasso picasso = new Picasso.Builder(context).downloader(downloader ).build();