android之okhttp

android之okhttp,先添加okhttp庫的依賴
在build.gradle文件的dependences加入
compile ‘com.squareup.okhttp3:okhttp:3.4.1’

發起“GET”

            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(adress)
                    .build();
            Response response=client.newCall(request).execute;

返回的數據保存在Response中

如果是發起一條“POST”

            OkHttpClient client = new OkHttpClient();
            RequestBody body=new FormBody.Builder()
                                        .add()      //鍵值對的方式添加需要發送的數據
                                        .build();
            Request request = new Request.Builder()
                    .url(adress)
                    .post(body)
                    .build();
            client.newCall(request).enqueue(callback);

將okhttp入公共類提供一個靜態方法
這樣每次使用時隻需調用靜態方法即可

public class okHttpUtil {

    public static void sendRequest(String adress, okhttp3.Callback callback) {

            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(adress)
                    .build();
            client.newCall(request).enqueue(callback);

    }
}

You May Also Like