Picasso load image with HTTP post

匿名 (未验证) 提交于 2019-12-03 01:23:02

问题:

My API needs some verification mechanism for verifying every HTTP request. The API have the functionality to load a image using HTTP post method. The post request body have contain a JSON object which is verified from the server side.

For that i need to include a json like this on the http post request body.

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

how can I do this with Picasso ?

回答1:

I got the solution from the hint given by Mr.Jackson Chengalai.

Create a Okhttp request interceptor

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 map = new HashMap();         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());     } } 

Create a Okhttp client add this interceptor

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

Create a Dowloader using this okhttp client

OkHttpDownloader = downloader = new OkHttpDownloader(okHttpClient) 

Build Picasso using this downloader

Picasso picasso = new Picasso.Builder(context).downloader(downloader ).build();  


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!