Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
690 views
in Technique[技术] by (71.8m points)

android - Picasso load image with HTTP post

My API having some verification mechanism for every HTTP request. One of the end-point have the functionality to load a image using HTTP post method. The post request body will 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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<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());
    }
}

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(); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...