OKHttp3簡單使用

超級無敵強發表於2018-05-09
import okhttp3.*;

import java.util.Map;
import java.util.concurrent.TimeUnit;

public final class HttpUtils {
    private final static OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(5, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .build();

    /**
     * get 請求
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static String execGet(String url) throws Exception {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    public static String execGet(String url, Map<String, String> params) throws Exception {
        if (url == null || url.length() == 0) {
            throw new IllegalArgumentException("url can not be null");
        }
        StringBuffer sb = new StringBuffer(url);
        if (params != null && !params.isEmpty()) {
            boolean isFirst = true;
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (isFirst) {
                    if (!url.contains("?")) {
                        sb.append("?");
                    }
                    isFirst = false;
                } else {
                    sb.append("&");
                }
                sb.append(entry.getKey() + "=" + entry.getValue());
            }
        }

        return execGet(sb.toString());
    }


    /**
     * post 請求
     *
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String execPost(String url, Map<String, String> params) throws Exception {
        FormBody.Builder builder = new FormBody.Builder();
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
            }
        }
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }


    /**
     * post 請求 json引數
     *
     * @param url
     * @param jsonParams
     * @return
     * @throws Exception
     */
    public static String execPost(String url, String jsonParams) throws Exception {
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , jsonParams);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

}