public class HttpUtils { public static final MediaType JSON = MediaType.parse("application/json;charset=utf-8"); public static String httpGet(String url,String authorization) throws IOException { OkHttpClient httpClient = new OkHttpClient(); Request request = new Request.Builder().url(url).addHeader("Authorization","Basic "+authorization).build(); Response response = httpClient.newCall(request).execute(); return response.body().string(); // 返回的是string 類型,json的mapper可以直接處理 } public static String httpPost(String url, String json,String authorization) throws IOException { OkHttpClient httpClient = new OkHttpClient(); RequestBody requestBody = RequestBody.create(JSON, json); Request request = new Request.Builder().url(url).addHeader("Authorization","Basic "+authorization).post(requestBody).build(); Response response = httpClient.newCall(request).execute(); return response.body().string(); } }
