okhttp常用工具类

在网络请求中常用的框架有

okhttp

android-async-http

volley

retrofit

这里介绍一下okhttp的使用

compile 'com.squareup.okhttp:okhttp:2.5.0'


package test.org.util;

import android.text.TextUtils;

import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class OkHttpUtil {
    private static final String CHARSET_NAME = "UTF-8";
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    private static final OkHttpClient okHttpClient = new OkHttpClient();

    static {
        okHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
    }

    /**
     * 同步get
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static String get(String url) throws Exception {
        Request request = new Request.Builder().url(url).build();

        Response response = execute(request);
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    /**
     * 同步get请求
     *
     * @param url
     * @param data
     * @return
     * @throws Exception
     */
    public static String get(String url, Map<String, String> data) throws Exception {
        url = getRequestUrl(url, data);
        Request request = new Request.Builder().url(url).build();

        Response response = execute(request);
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    /**
     * 异步get请求
     *
     * @param url
     * @param responseCallback
     * @return
     * @throws Exception
     */
    public static void get(String url, Callback responseCallback) throws Exception {
        Request request = new Request.Builder().url(url).build();

        enqueue(request, responseCallback);
    }

    /**
     * 异步get
     *
     * @param url
     * @param data
     * @param responseCallback
     * @return
     * @throws Exception
     */
    public static void get(String url, Map<String, String> data, Callback responseCallback) throws Exception {
        url = getRequestUrl(url, data);
        Request request = new Request.Builder().url(url).build();

        enqueue(request, responseCallback);
    }

    /**
     * 同步post json数据
     *
     * @param url
     * @param json
     * @return
     * @throws IOException
     */
    public static String post(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder().url(url).post(body).build();

        Response response = execute(request);
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    /**
     * 同步post 键值对数据
     *
     * @param url
     * @param data
     * @return
     * @throws IOException
     */
    public static String post(String url, Map<String, String> data) throws IOException {
        FormEncodingBuilder formBuilder = new FormEncodingBuilder();
        for (Map.Entry<String, String> item : data.entrySet()) {
            formBuilder.add(item.getKey(), item.getValue());
        }

        RequestBody body = formBuilder.build();
        Request request = new Request.Builder().url(url).post(body).build();

        Response response = execute(request);
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    /**
     * 异步post json
     *
     * @param url
     * @param json
     * @param responseCallback
     * @throws IOException
     */
    public static void post(String url, String json, Callback responseCallback) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder().url(url).post(body).build();

        enqueue(request, responseCallback);
    }

    /**
     * 异步post key-value
     *
     * @param url
     * @param data
     * @param responseCallback
     * @throws IOException
     */
    public static void post(String url, Map<String, String> data, Callback responseCallback) throws IOException {
        FormEncodingBuilder formBuilder = new FormEncodingBuilder();
        for (Map.Entry<String, String> item : data.entrySet()) {
            formBuilder.add(item.getKey(), item.getValue());
        }

        RequestBody body = formBuilder.build();
        Request request = new Request.Builder().url(url).post(body).build();

        enqueue(request, responseCallback);
    }

    /**
     * 同步put
     *
     * @param url
     * @param json
     * @return
     * @throws IOException
     */
    public static String put(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);

        Request request = new Request.Builder().url(url).put(body).build();

        Response response = execute(request);
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    /**
     * 同步put key-value
     *
     * @param url
     * @param data
     * @return
     * @throws IOException
     */
    public static String put(String url, Map<String, String> data) throws IOException {
        FormEncodingBuilder formBuilder = new FormEncodingBuilder();
        for (Map.Entry<String, String> item : data.entrySet()) {
            formBuilder.add(item.getKey(), item.getValue());
        }

        RequestBody body = formBuilder.build();
        Request request = new Request.Builder().url(url).put(body).build();

        Response response = execute(request);
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    /**
     * 异步put json
     *
     * @param url
     * @param json
     * @throws IOException
     */
    public static void put(String url, String json, Callback responseCallback) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);

        Request request = new Request.Builder().url(url).put(body).build();
        enqueue(request, responseCallback);
    }

    /**
     * 异步put key-value
     *
     * @param url
     * @param data
     * @param responseCallback
     * @throws IOException
     */
    public static void put(String url, Map<String, String> data, Callback responseCallback) throws IOException {
        FormEncodingBuilder formBuilder = new FormEncodingBuilder();
        for (Map.Entry<String, String> item : data.entrySet()) {
            formBuilder.add(item.getKey(), item.getValue());
        }

        RequestBody body = formBuilder.build();
        Request request = new Request.Builder().url(url).put(body).build();

        enqueue(request, responseCallback);
    }

    /**
     * 通用同步请求。
     *
     * @param request
     * @return
     * @throws IOException
     */
    public static Response execute(Request request) throws IOException {
        return okHttpClient.newCall(request).execute();
    }

    /**
     * 通用异步请求
     *
     * @param request
     * @param responseCallback
     */
    public static void enqueue(Request request, Callback responseCallback) {
        okHttpClient.newCall(request).enqueue(responseCallback);
    }

    /**
     * 开启异步线程访问网络, 且不在意返回结果(实现空callback)
     *
     * @param request
     */
    public static void enqueue(Request request) {
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Response arg0) throws IOException {
                //
            }

            @Override
            public void onFailure(Request arg0, IOException arg1) {
                //
            }
        });
    }

    public static String getStringFromServer(String url) throws IOException {
        Request request = new Request.Builder().url(url).build();
        Response response = execute(request);
        if (response.isSuccessful()) {
            String responseUrl = response.body().string();
            return responseUrl;
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }


    /**
     * 这里使用了HttpClinet的API。只是为了方便
     *
     * @param params
     * @return
     */
    public static String formatParams(List<BasicNameValuePair> params) {
        return URLEncodedUtils.format(params, CHARSET_NAME);
    }

    /**
     * 为HttpGet 的 url 方便的添加多个name value 参数。
     *
     * @param url
     * @param params
     * @return
     */
    public static String attachHttpGetParams(String url, List<BasicNameValuePair> params) {
        return url + "?" + formatParams(params);
    }

    /**
     * 为HttpGet 的 url 方便的添加1个name value 参数。
     *
     * @param url
     * @param name
     * @param value
     * @return
     */
    public static String attachHttpGetParam(String url, String name, String value) {
        return url + "?" + name + "=" + value;
    }

    /**
     * get方式URL拼接
     *
     * @param url
     * @param map
     * @return
     */
    private static String getRequestUrl(String url, Map<String, String> map) {
        if (map == null || map.size() == 0) {
            return url;
        } else {
            StringBuilder newUrl = new StringBuilder(url);
            if (url.indexOf("?") == -1) {
                newUrl.append("?rd=" + Math.random());
            }

            for (Map.Entry<String, String> item : map.entrySet()) {
                if (false == TextUtils.isEmpty(item.getKey().trim())) {
                    try {
                        newUrl.append("&" + item.getKey().trim() + "=" + URLEncoder.encode(String.valueOf(item.getValue().trim()), "UTF-8"));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            return newUrl.toString();
        }
    }
}

这个工具类很不错:

https://github.com/hongyangAndroid/okhttp-utils

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: OKHttp3 是一个开源的用于HTTP请求的工具类库,是Square公司开发的。它构建在OkIO库的基础上,并且提供了强大且灵活的功能,用于进行网络请求和数据交互。 OKHttp3 支持GET、POST、PUT、DELETE等常用的HTTP请求方法,可以方便地与Web服务器进行数据交互。它提供了丰富的功能,如连接池管理、请求重试、请求拦截器、响应拦截器等,能够满足各种复杂的网络请求需求。 使用OKHttp3工具类进行网络请求也十分简单。首先,我们需要创建一个OKHttpClient实例,可以设置一些配置,如连接超时时间、读取超时时间等。然后,我们可以通过OKHttpClient生成一个Request对象,设置请求的URL、请求方法以及请求体等。接下来,使用这个Request对象来创建一个Call对象,再调用execute或enqueue方法发送请求。最后,我们可以通过Response对象获取到服务器返回的响应数据。 除了基本的网络请求功能,OKHttp3还支持多线程并发请求、文件上传和下载、WebSocket等高级特性。它的设计易于扩展和定制,可以与其他框架(如RxJava、Retrofit)配合使用,进一步简化网络请求的操作。 总之,OKHttp3是一个功能强大、灵活易用的工具类库,能够帮助我们轻松进行网络请求和数据交互。无论是简单的GET请求还是复杂的多线程请求,OKHttp3都能够胜任,并且具备良好的性能和稳定性。 ### 回答2: OkHttp3 是一个开源的基于 Java 的 HTTP 客户端工具类库,它提供了简洁的 API 接口和高效的网络通信能力。 首先,OkHttp3 内部实现了连接池和请求复用功能,可以重用之前的连接和请求,从而减少网络连接和请求的开销,提高网络性能。它还支持 HTTP/2 和 SPDY,能够多路复用多个请求,提升并发访问效率。 OkHttp3 的 API 设计简洁易用,提供了丰富的功能,如异步请求、同步请求、文件上传、文件下载、Cookie 管理等。我们可以通过建立 OkHttpClient 对象,设置一些配置信息,如超时时间、拦截器等,然后通过创建 Request 对象来发起请求,并通过回调方式获取服务器返回的响应。 使用 OkHttp3,我们可以轻松地处理各种类型的网络请求,包括 GET、POST、PUT、DELETE 等,并可以通过设置 Header、Body 参数来自定义请求内容。OkHttp3 还提供了缓存机制,我们可以通过配置缓存策略,减少对服务器的频繁请求,同时也可以配置自定义的拦截器,对请求和响应进行处理和修改。 另外,OkHttp3 还支持自动设置代理、支持网络请求的重试和重定向,以及支持自定义的证书校验等安全性功能。 总之,OkHttp3 是一个功能强大、易用且高效的网络请求工具类库,广泛应用于 Android 和 Java 开发中。它提供了丰富的功能和高性能的网络通信能力,帮助我们方便快捷地发起各种类型的网络请求,并处理返回的响应数据。 ### 回答3: okhttp3 是一个流行的开源网络请求框架,主要用于在 Android 平台上发送和接收 HTTP 请求。 okhttp3 工具类可以帮助我们更方便地使用和管理 okhttp3,提供了一系列简化了的方法和功能,使我们能够更高效地进行网络请求的处理。 首先,okhttp3 工具类可以帮助我们创建 OkHttpClient 实例,这是 okhttp3 中的核心对象,用于发送和接收请求。我们可以通过设置不同的配置参数,如超时时间、连接数限制等,来满足不同的需求。 接下来,okhttp3 工具类提供了简化了的方法,如 GET、POST 等,用于发送不同类型的请求。我们只需提供请求的地址和参数,工具类就会自动构建请求对象,并将响应结果以回调方式返回。 此外,okhttp3 工具类还支持多线程并发请求的功能。我们可以通过设置线程池来同时发送多个请求,从而提高并发处理能力。 okhttp3 工具类还提供了拦截器的功能,可用于在发送和接收请求的过程中进行一些自定义的操作,如参数加密、日志记录等。我们可以通过自定义拦截器来实现这些功能,并将其添加到 OkHttpClient 实例中。 总的来说,okhttp3 工具类提供了一系列简化了的方法和功能,使我们能够更方便地使用 okhttp3 进行网络请求。它大大简化了我们的开发流程,减少了代码量,并且具有高效和可靠的性能。无论是在 Android 开发中,还是在其他需要进行网络请求的场景中,okhttp3 工具类都是一个值得推荐的选择。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值