1. 程式人生 > >OkHttp的非同步get, post請求

OkHttp的非同步get, post請求

新增依賴

新增許可權:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
/>

1.get請求獲取慕課網首頁資料

public void qcokhttpget(View view) { //get請求獲取慕課網首頁資料
    Request request = new Request.Builder()
            .get() //return method("GET", null);
            .url("http://www.imooc.com/")
            .build();

    OkHttpClient okHttpClient = new OkHttpClient();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.i("mydate" , "failure");
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException { //不在ui執行緒
            String str = response.body().string();
            Log.i("mydate" , str);
        }
    });
}

2.get方式下載圖片

//okhttp的get方式下載圖片
private void xiazaiwj() {
    String url = "http://img.my.csdn.net/uploads/201603/26/1458988468_5804.jpg";
    Request request = new Request.Builder() //Builder原始碼中預設method是GET
            .url(url)
            .build();
    OkHttpClient okhttp = new OkHttpClient();
    okhttp.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response){
            InputStream inputstream = response.body().byteStream();
            FileOutputStream fileoutputstream = null;
            String filepath = "";
            try{
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                    filepath = Environment.getExternalStorageDirectory().getAbsolutePath();
                } else{
                    filepath = getFilesDir().getAbsolutePath();
                }
                Log.i("mydate" , filepath);
                File file = new File(filepath , "liuyan.jpg");
                Log.i("mydate" , "bu wei kong");
                fileoutputstream = new FileOutputStream(file);
                byte[] buffer = new byte[2048];
                int len = 0;
                while((len = inputstream.read(buffer)) != -1){
                    fileoutputstream.write(buffer , 0 , len);
                }
                fileoutputstream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
}

3.post表單

//post表單
//post請求name=myliuyan age=22 並在eclipse的servlet中打印出來
//如果是寫成get請求,則url= http://192.168.31.223:8080/MyServlet2/myserv?name=myliuyan&age=22
public void qcokhttppost(View view) {
    RequestBody requestBody = new FormBody.Builder()
            .add("name" , "myliuyan")
            .add("age" , "22")
            .build();

    Request request = new Request.Builder()
            .url("http://192.168.31.223:8080/MyServlet2/myserv")
            .post(requestBody) //return method("post", null);
            .build();
    OkHttpClient okhttp = new OkHttpClient();
    Call call = okhttp.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.i("mydate" , "失敗");
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            String str = response.body().string();
            Log.i("mydate" , str);
        }
    });
}

4.post一個string

//post一個string
public void okhttppoststring(View view) {
    //RequestBody.creat中的引數1代表型別,這裡為string型別 , 第2引數表示型別對應的值.(上傳檔案,就是檔案型別加檔案)
    RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain;charset=utf-8")  , "這只是一個string" );
    Request request = new Request.Builder()
            .url("http://192.168.31.223:8080/MyServlet2/myserv")
            .post(requestBody)  //post一個string
            .build();
    OkHttpClient okHttpClient = new OkHttpClient();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.i("mydate" , "failure");
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException { //不在ui執行緒
            String str = response.body().string();
            Log.i("mydate" , str);
        }
    });

}

5.post一個file檔案

//post一個file檔案
public void okhttppostfile(View view) {
    File file = new File(Environment.getExternalStorageDirectory() , "liuyan.jpg"); //SD卡儲存上有這個檔案 ,還要相關許可權開啟
    if (!file.exists()){
        Log.i("mydate" , "file not exist");
        return;
    }
    //RequestBody.creat中的引數1代表型別,這裡為(上傳檔案,就是 檔案型別 加 檔案 )
    RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream")  , file );
    Request request = new Request.Builder()
            .url("http://192.168.31.223:8080/MyServlet2/myserv")
            .post(requestBody)  //post
            .build();
    OkHttpClient okHttpClient = new OkHttpClient();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.i("mydate" , "failure");
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException { //不在ui執行緒
            String str = response.body().string();
            Log.i("mydate" , str);
        }
    });
}

6.這個服務端不知道寫,所以不知道MultipartBody裡面的東西怎麼取出來。以後有時間再研究.

//post檔案和相關引數,同時上傳
public void okhttppostfileandparams(View view) {
    File file = new File(Environment.getExternalStorageDirectory() , "liuyan.jpg"); //SD卡儲存上有這個檔案 ,還要相關許可權開啟
    if (!file.exists()){
        Log.i("mydate" , "file not exist");
        return;
    }
    //RequestBody.creat中的引數1代表型別,這裡為(上傳檔案,就是 檔案型別 加 檔案 )
    //RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream")  , file );

    RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("name" , "liuyan")//AA
            .addFormDataPart("age" , "22") //BB
            .addFormDataPart("image" , "my.jpg" , RequestBody.create(MediaType.parse("application/octet-stream")  , file ))
            .build(); //AAaddFormDataPart的第一個引數為key,第2引數為value
    //BBaddFormDataPart的第一個引數為key,第二個引數為filename(value),第三個引數為requestbody(檔案,json,string等)
    //key在eclipse的servlet中必須要一致
    Request request = new Request.Builder()
            .url("http://192.168.31.223:8080/MyServlet2/myserv")
            .post(requestBody)  //post
            .build();
    OkHttpClient okHttpClient = new OkHttpClient();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.i("mydate" , "failure");
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException { //不在ui執行緒
            String str = response.body().string();
            Log.i("mydate" , str);
        }
    });
}