java 使用okhttp 實現get post請求發送


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();
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM