package com.zzwtec.wechat.util; import okhttp3.*; import java.io.IOException; import java.util.Map; import java.util.concurrent.TimeUnit; /** * Created by Xin.L on 2017/9/22. */ public class HttpUtil { private static OkHttpClient client = new OkHttpClient().newBuilder().connectTimeout(1, TimeUnit.SECONDS).readTimeout(10, TimeUnit.SECONDS).build(); private static final MediaType TEXT_XML = MediaType.parse("text/xml; charset=utf-8"); private static final MediaType TEXT_PLAIN = MediaType.parse("text/plain; charset=utf-8"); private static final MediaType APPLICATION_JSON = MediaType.parse("application/json; charset=utf-8"); public static String postJSON(String url, Map headers, String json) { Request.Builder builder = new Request.Builder(); builder.url(url).post(RequestBody.create(APPLICATION_JSON, json)); if (headers != null && headers.size() != 0) { for (Map.Entry entry : headers.entrySet()) { builder.addHeader(entry.getKey(), entry.getValue()); } } Response response = execute(builder.build()); return getBody(response); } public static Response execute(Request request) { try { return client.newCall(request).execute(); } catch (IOException e) { throw new RuntimeException(e); } } public static String getBody(Response response) { try { return response.body().string(); } catch (IOException e) { throw new RuntimeException(e); } finally { if (response != null) { response.close(); } } } }