Java OkHttp使用

本文使用eclipse編輯器,gradle依賴jar,如若未配置此環境,請轉Java Eclipse配置gradle編譯項目配置好環境后再查看此文

  1. 在build.gradle中添加依賴
    compile 'com.squareup.okhttp3:okhttp:3.8.1'
  2. 同步Get請求
    /**
     * 同步get請求
     */
    public static void syncGet() throws Exception{
        String urlBaidu = "http://www.baidu.com/";
        OkHttpClient okHttpClient = new OkHttpClient(); // 創建OkHttpClient對象
        Request request = new Request.Builder().url(urlBaidu).build(); // 創建一個請求
        Response response = okHttpClient.newCall(request).execute(); // 返回實體
        if (response.isSuccessful()) { // 判斷是否成功
            /**獲取返回的數據,可通過response.body().string()獲取,默認返回的是utf-8格式;
             * string()適用于獲取小數據信息,如果返回的數據超過1M,建議使用stream()獲取返回的數據,
             * 因為string() 方法會將整個文檔加載到內存中。*/
            System.out.println(response.body().string()); // 打印數據
        }else {
            System.out.println("失敗"); // 鏈接失敗
        }
    }
  1. 異步Get請求
    /**
     * 異步Get請求
     */
    public static void asyncGet() {
        String urlBaidu = "http://www.baidu.com/";
        OkHttpClient okHttpClient = new OkHttpClient(); // 創建OkHttpClient對象
        Request request = new Request.Builder().url(urlBaidu).build(); // 創建一個請求
        okHttpClient.newCall(request).enqueue(new Callback() { // 回調 
            
            public void onResponse(Call call, Response response) throws IOException {
                // 請求成功調用,該回調在子線程
                System.out.println(response.body().string());
            }
            
            public void onFailure(Call call, IOException e) {
                // 請求失敗調用
                System.out.println(e.getMessage());
            }
        });
    }

4.Post提交表單

    /**
     * Post提交表單
     */
    public static void postFromParameters() {
        String url = "http://v.juhe.cn/wepiao/query"; // 請求鏈接
        String KEY = "9488373060c8483a3ef6333353fdc7fe"; // 請求參數
        OkHttpClient okHttpClient = new OkHttpClient(); // OkHttpClient對象
        RequestBody formBody = new FormBody.Builder().add("key", KEY).build(); // 表單鍵值對
        Request request = new Request.Builder().url(url).post(formBody).build(); // 請求
        okHttpClient.newCall(request).enqueue(new Callback() {// 回調

            public void onResponse(Call call, Response response) throws IOException {
                System.out.println(response.body().string());//成功后的回調
            }

            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());//失敗后的回調
            }
        });
    }
  1. Post提交字符串
    /**
     * Post提交字符串
     * 使用Post方法發送一串字符串,但不建議發送超過1M的文本信息
     */
    public static void postStringParameters(){
        MediaType MEDIA_TYPE = MediaType.parse("text/text; charset=utf-8");
        String url = "http://v.juhe.cn/wepiao/query"; // 請求鏈接
        OkHttpClient okHttpClient = new OkHttpClient(); // OkHttpClient對象
        String string = "key=9488373060c8483a3ef6333353fdc7fe"; // 要發送的字符串
        /**
         * RequestBody.create(MEDIA_TYPE, string)
         * 第二個參數可以分別為:byte[],byteString,File,String。
         */
        Request request = new Request.Builder().url(url)
                    .post(RequestBody.create(MEDIA_TYPE,string)).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println(response.body().string());
            }
            
            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());
            }
        }); 
    }
  1. Gson解析Response的Gson對象
    /**
     * Gson解析Response的Gson對象
     */
    public static void gsonResponsePost() {
        String url = "http://v.juhe.cn/wepiao/query"; // 請求鏈接
        String KEY = "9488373060c8483a3ef6333353fdc7fe"; // 請求參數
        OkHttpClient okHttpClient = new OkHttpClient(); // OkHttpClient對象
        RequestBody formBody = new FormBody.Builder().add("key", KEY).build(); // 表單鍵值對
        Request request = new Request.Builder().url(url).post(formBody).build(); // 請求
        okHttpClient.newCall(request).enqueue(new Callback() {// 回調

            public void onResponse(Call call, Response response) throws IOException {
                //成功后的回調
                Gson gson = new Gson();
                Info info = gson.fromJson(response.body().string(), Info.class);
                System.out.println(info.toString());
            }

            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());//失敗后的回調
            }
        });
    }
    /**
     * Java Bean
     */
    public class Info{
        int error_code; //狀態碼
        String reason; // 返回狀態文字
        Result result; // 頁面URL
        @Override
        public String toString() {
            return "Info [error_code=" + error_code + ", reason=" + reason + ", result=" + result.toString() + "]";
        }
    }
    /**
     * Java Bean
     */
    public class Result{
        String h5url;
        String h5weixin;
        @Override
        public String toString() {
            return "Result [h5url=" + h5url + ", h5weixin=" + h5weixin + "]";
        }   
    }
  1. okhttp3 設置超時時間
    /**
     * 設置超時
     * @throws IOException 
     */
    public static void timeOutPost() throws IOException {
        OkHttpClient client = new OkHttpClient.Builder()
                                    .connectTimeout(10, TimeUnit.SECONDS)//設置鏈接超時
                                    .writeTimeout(10, TimeUnit.SECONDS) // 設置寫數據超時
                                    .readTimeout(30, TimeUnit.SECONDS) // 設置讀數據超時
                                    .build();
        Request request = new Request.Builder().url("http://www.baidu.com/").build();

        Response response = client.newCall(request).execute();
        System.out.println("Response completed: " + response);
    }
  1. 緩存設置
    /**
     * 緩存設置
     * @throws Exception
     */
    public static void cachePost() throws Exception {
        File sdcache = new File("D:/file");
        int cacheSize = 10 * 1024 * 1024; // 10 MiB
        OkHttpClient client = new OkHttpClient()
                .Builder()
                .cache(new Cache(sdcache.getAbsoluteFile(), cacheSize))
                .build();
        Request request = new Request.Builder()
                .url("http://publicobject.com/helloworld.txt")
                .build();

        Response response1 = client.newCall(request).execute();
        if (!response1.isSuccessful()) throw new IOException("Unexpected code " + response1);

        String response1Body = response1.body().string();
        System.out.println("Response 1 response:          " + response1);
        System.out.println("Response 1 cache response:    " + response1.cacheResponse());
        System.out.println("Response 1 network response:  " + response1.networkResponse());

        request = request.newBuilder().cacheControl(CacheControl.FORCE_NETWORK).build();
        Response response2 = client.newCall(request).execute();
        if (!response2.isSuccessful()) throw new IOException("Unexpected code " + response2);

        String response2Body = response2.body().string();
        System.out.println("Response 2 response:          " + response2);
        System.out.println("Response 2 cache response:    " + response2.cacheResponse());
        System.out.println("Response 2 network response:  " + response2.networkResponse());

        System.out.println("Response 2 equals Response 1? " + response1Body.equals(response2Body));
    }

打印結果:

Response 1 response:          Response{protocol=http/1.1, code=200, message=OK, url=https://publicobject.com/helloworld.txt}
Response 1 cache response:    Response{protocol=http/1.1, code=200, message=OK, url=https://publicobject.com/helloworld.txt}
Response 1 network response:  null
Response 2 response:          Response{protocol=http/1.1, code=200, message=OK, url=https://publicobject.com/helloworld.txt}
Response 2 cache response:    null
Response 2 network response:  Response{protocol=http/1.1, code=200, message=OK, url=https://publicobject.com/helloworld.txt}
Response 2 equals Response 1? true
  1. 復用OkHttpClient
    /**
     * 所有HTTP請求的代理設置,超時,緩存設置等都需要在OkHttpClient中設置。 如果需要更改一個請求的配置,可以使用
     * OkHttpClient.newBuilder()獲取一個builder對象,
     * 該builder對象與原來OkHttpClient共享相同的連接池,配置等。
     */
    public static void shareClient() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url("http://www.baidu.com/").build();

        try {
            // Copy to customize OkHttp for this request.
            OkHttpClient copy = client.newBuilder().readTimeout(500, TimeUnit.MILLISECONDS).build();
            Response response = copy.newCall(request).execute();
            System.out.println("Response 1 succeeded: " + response);
        } catch (IOException e) {
            System.out.println("Response 1 failed: " + e);
        }

        try {
            // Copy to customize OkHttp for this request.
            OkHttpClient copy = client.newBuilder().readTimeout(3000, TimeUnit.MILLISECONDS).build();
            Response response = copy.newCall(request).execute();
            System.out.println("Response 2 succeeded: " + response);
        } catch (IOException e) {
            System.out.println("Response 2 failed: " + e);
        }
    }
  1. OkHttp3處理驗證
    /**
     * 登錄驗證
     * @throws IOException
     */
    public static void authenticatorPost() throws IOException {
        OkHttpClient okHttpClient = 
                new OkHttpClient
                .Builder()
                .authenticator(new Authenticator() {
                    
                    public Request authenticate(Route route, Response response) throws IOException { 
                        System.out.println(response.challenges().toString());
                        String credential = Credentials.basic("jesse", "password1");
                        return response
                                .request()
                                .newBuilder()
                                .addHeader("Authorization", credential)
                                .build();
                    }
                })
                .build();
        Request request = new Request.Builder().url("http://publicobject.com/secrets/hellosecret.txt").build();
        Response response = okHttpClient.newCall(request).execute();
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

        System.out.println(response.body().string());
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容