huangmaohuoshaoxuexia/Note

OKhttp3 基础类

Opened this issue · 0 comments

public class OkHttpUtil {
private static final OkHttpClient mOkHttpClient = new OkHttpClient();
private static final MediaType type = MediaType.parse("text/html;charset=gb2312");

static {
    mOkHttpClient.newBuilder().connectTimeout(30, TimeUnit.SECONDS);
}

/**
 * 该不会开启异步线程。
 *
 * @param request
 * @return
 * @throws IOException
 */
public static Response execute(Request request) throws IOException {
    return mOkHttpClient.newCall(request).execute();
}

/**
 * 根据url 和  params 获取到服务器数据
 * @param url
 * @param params
 * @return
 * @throws IOException
 */
public static String getStringFromServer(String url, Map<String, String> params) throws IOException {
    Request request = new Request.Builder().url(url).post(requestBody(params)).build();
    Response response = execute(request);
    if (response.isSuccessful()) {
        String responseUrl = response.body().string();
        return responseUrl;
    } else {
        throw new IOException("Unexpected code " + response);
    }
}

/**
 * map 转 RequestBody
 * @param params
 * @return
 */
public static RequestBody requestBody(Map<String, String> params) {
    String content = "";
    Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<String, String> entry = it.next();
        content += entry.getKey() + "=" + entry.getValue();
        if (it.hasNext()) {
            content += "&";
        }
    }
    return RequestBody.create(type, content);
}