美文网首页
okhttp简单使用

okhttp简单使用

作者: xujunhe | 来源:发表于2016-07-01 15:29 被阅读1070次

版权声明:本文为博主原创文章,未经博主允许不得转载。

OkHttp的项目地址

github https://github.com/square/okhttp
官网 http://square.github.io/okhttp/

使用前配置

MAVEN方式

<dependency> 
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId> 
    <version>3.3.1</version>
</dependency>

GRADLE方式

compile 'com.squareup.okhttp3:okhttp:3.3.1' //目前最新版

如果需要jar包可以去官网下载。

get使用

1.同步请求



        String url = "https://publicobject.com/helloworld.txt";
        //初始化okhttp客户端
        OkHttpClient client  = new OkHttpClient();
        //创建请求体
        Request request = new Request.Builder().url(url).get().build();
        Call newCall = client.newCall(request);
        //执行请求
        Response response = newCall.execute();  
        //获取服务器响应数据
        if (response.isSuccessful()) {
            String result = response.body().string();
            System.out.println(result);
        }

2.异步请求

        //初始化okhttp客户端
        OkHttpClient client  = new OkHttpClient();
        //创建请求体
        Request request = new Request.Builder().url(url).get().build();
        Call newCall = client.newCall(request);
        //调用异步执行
        newCall.enqueue(new Callback() {
            
            //在获取服务器响应结果
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String result = response.body().string();
                    System.out.println(result);
                }               
            }
            //失败结果
            @Override
            public void onFailure(Call call, IOException ex) {
                //这里处理错误
            }
        });

post使用

1.同步请求(不包含文件请求)

        
        String url = "http://example.com";
        //初始化OkHttp客户端
        OkHttpClient client = new OkHttpClient();
        //创建上传参数
        Builder builder = new FormBody.Builder()
        .add("userName", "xxx").add("pwd", "xxx");
        RequestBody requestBody = builder.build();
        Request request = new Request.Builder().url(url).post(requestBody)
                .build();
        Call newCall = client.newCall(request);
        Response response = newCall.execute();
        if (response.isSuccessful()) {
            //这里是返回结果
            String string = response.body().string();
            System.out.println(string);
        }

2.异步请求(不包含文件请求)

        
        String url = "http://example.com";
        //初始化OkHttp客户端
        OkHttpClient client = new OkHttpClient();
        //创建上传参数
        Builder builder = new FormBody.Builder()
        .add("userName", "xxx").add("pwd", "xxx");
        RequestBody requestBody = builder.build();
        Request request = new Request.Builder().url(url).post(requestBody)
                .build();
        Call newCall = client.newCall(request);
        newCall.enqueue(new Callback() {
            
            //返回结果
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String string = response.body().string();
                    System.out.println(string);
                }
            }
            
            //失败
            @Override
            public void onFailure(Call call, IOException ex) {
                 //这里处理错误
            }
        });

3.post同步上传文件


        String url = "http://example.com";
        // 初始化OkHttp客户端
        OkHttpClient client = new OkHttpClient();
        okhttp3.MultipartBody.Builder builder = new MultipartBody.Builder();
        // 上传的参数
        builder.addFormDataPart("userName", "xxx");
        //内容类型
        String contentType = "image/jpeg; charset=UTF-8";
        String key = "img";
        //需要上传的文件
        File file = new File("icon.jpg");
        if (file != null && file.exists()) {
            RequestBody body = RequestBody.create(MediaType.parse(contentType),
                    file);
            builder.addFormDataPart(key, file.getName(), body);
        }
        RequestBody requestBody = builder.build();
        Request request = new Request.Builder().url(url).post(requestBody)
                .build();
        Call newCall = client.newCall(request);
        Response response = newCall.execute();
        if (response.isSuccessful()) {
            String string = response.body().string();
            System.out.println(string);
        }

4.post异步上传文件

        String url = "http://example.com";
        // 初始化OkHttp客户端
        OkHttpClient client = new OkHttpClient();
        okhttp3.MultipartBody.Builder builder = new MultipartBody.Builder();
        // 上传的参数
        builder.addFormDataPart("userName", "xxx");
        //内容类型
        String contentType = "image/jpeg; charset=UTF-8";
        String key = "img";
        //需要上传的文件
        File file = new File("icon.jpg");
        if (file != null && file.exists()) {
            RequestBody body = RequestBody.create(MediaType.parse(contentType),
                    file);
            builder.addFormDataPart(key, file.getName(), body);
        }
        RequestBody requestBody = builder.build();
        Request request = new Request.Builder().url(url).post(requestBody)
                .build();
        Call newCall = client.newCall(request);
        newCall.enqueue(new Callback() {
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String string = response.body().string();
                    System.out.println(string);
                }
                
            }
            
            @Override
            public void onFailure(Call arg0, IOException arg1) {
                // 这里是错误信息
                
            }
        });

简单封装

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.FormBody.Builder;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * OKHttp请求工具类
 * 
 * @author xujunhe
 * 
 */
public class OkhttpUtils {

    private static final OkHttpClient client = new OkHttpClient();

    /**
     * get请求
     * 
     * @param url
     *            请求地址
     * @param params
     *            请求参数
     * @return 返回结果
     * @throws IOException
     */
    public static Response get(String url, Map<String, String> params)
            throws IOException {
        return createGetCall(url, params).execute();
    }

    /**
     * get异步请求
     * 
     * @param url
     *            请求地址
     * @param params
     *            请求参数
     * @return 返回结果
     * @throws IOException
     */
    public static void get(String url, Map<String, String> params,
            Callback callback) {
        createGetCall(url, params).enqueue(callback);
    }

    /**
     * post同步请求
     * 
     * @param url
     *            请求地址
     * @param params
     *            请求参数
     * @return 返回结果
     * @throws IOException
     */
    public static Response post(String url, Map<String, String> params)
            throws IOException {
        return createPostCall(url, params).execute();
    }

    /**
     * post异步请求
     * 
     * @param url
     *            请求地址
     * @param params
     *            请求参数
     * @param callback
     *            返回结果
     */
    public static void post(String url, Map<String, String> params,
            Callback callback) {
        createPostCall(url, params).enqueue(callback);
    }

    /**
     * post同步请求
     * 
     * @param url
     *            请求地址
     * @param params
     *            提交参数
     * @param files
     *            提交文件
     * @return 返回结果
     * @throws IOException
     */
    public static Response post(String url, Map<String, String> params,
            Map<String, File> files) throws IOException {

        return createPostCall(url, params, files).execute();

    }

    /**
     * post异步请求
     * 
     * @param url
     *            请求地址
     * @param params
     *            提交参数
     * @param files
     *            提交文件
     * @param callback
     *            返回结果
     */
    public static void post(String url, Map<String, String> params,
            Map<String, File> files, Callback callback) {
        createPostCall(url, params, files).enqueue(callback);
    }

    private static Call createGetCall(String url, Map<String, String> params) {
        String urlParams = buildUrlParams(params);
        Request request = new Request.Builder().get()
                .url(url + '?' + urlParams).build();
        return client.newCall(request);
    }

    private static String buildUrlParams(Map<String, String> params) {
        if (params == null || params.isEmpty()) {
            return null;
        }
        StringBuilder result = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (result.length() > 0)
                result.append("&");
            result.append(entry.getKey());
            result.append("=");
            result.append(entry.getValue());
        }
        return result.toString();
    }

    private static Call createPostCall(String url, Map<String, String> params,
            Map<String, File> files) {
        okhttp3.MultipartBody.Builder builder = new MultipartBody.Builder();
        // 上传的参数
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.addFormDataPart(entry.getKey(), entry.getValue());
            }
        }
        // 设置上传的文件
        if (files != null && !files.isEmpty()) {

            for (Entry<String, File> entry : files.entrySet()) {
                File file = entry.getValue();
                String contentType = null;

                boolean isPng = file.getName().endsWith(".png")
                        || file.getName().endsWith(".PNG");

                if (isPng) {
                    contentType = "image/png; charset=UTF-8";
                }

                boolean isJpg = file.getName().endsWith(".jpg")
                        || file.getName().endsWith(".JPG")
                        || file.getName().endsWith(".jpeg")
                        || file.getName().endsWith(".JPEG");
                if (isJpg) {
                    contentType = "image/jpeg; charset=UTF-8";
                }
                if (file != null && file.exists()) {
                    RequestBody body = RequestBody.create(
                            MediaType.parse(contentType), file);
                    builder.addFormDataPart(entry.getKey(), file.getName(),
                            body);
                }
            }
        }
        RequestBody requestBody = builder.build();
        Request request = new Request.Builder().url(url).post(requestBody)
                .build();
        return client.newCall(request);
    }

    private static Call createPostCall(String url, Map<String, String> params) {
        Builder builder = new FormBody.Builder();
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
            }
        }
        RequestBody requestBody = builder.build();
        Request request = new Request.Builder().url(url).post(requestBody)
                .build();
        return client.newCall(request);
    }

}


相关文章

网友评论

      本文标题:okhttp简单使用

      本文链接:https://www.haomeiwen.com/subject/dejfjttx.html