淺析 - okHttp3使用總結

目錄

okHttp

尊重每個人的付出,轉載請點這裏: http://blog.csdn.net/hanj456/article/details/52424733

注意事項:

  • okHttp3和之前的版本上相比較有些小改動,例如:
    FormEncodingBuilder 被替換成 FormBody ,MultipartBuilder 被替換成 RequestBody;
    okhttp使用MultipartBuilder,FormEncodingBuilder構建post消息體,最終構建出來的都是RequestBody,而okhttp3增加了RequestBody的子類,構造器放到了RequestBody的子類中,MultipartBody.Builder既可以添加表單數據,也可以添加文件等二進制數據

解析類型

MediaType.parse("image/png");  //圖片類型
MediaType.parse("audio/mp3");  //音頻類型
MediaType.parse("video/mp4");  //視頻類型
MediaType.parse("text/x-markdown; charset=utf-8"); //markdown文本類型
MediaType.parse("application/json; charset=utf-8"); //Json數據類型

get請求登錄

/**
 * get請求登錄
 *
 * @param view
 */
public void getLogin(View view) {
    new Thread() {
        @Override
        public void run() {
            super.run();
            OkHttpClient client = new OkHttpClient();
            final Request request = new Request.Builder()
                    .url("http://10.0.2.2:8080/0903/LoginServlet?name=jack&pwd=123")
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Log.i(TAG, "onResponse: "+response.body().string());
                }
            });
        }
    }.start();
}

get請求獲取圖片


    /**
     * get請求獲取圖片
     *
     * @param view
     */
    public void getImage(View view) {

        new Thread() {
            @Override
            public void run() {
                super.run();
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("http://10.0.2.2:8080/0903/tang3.jpg")
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (response.isSuccessful()){
                            //get the stream
                            InputStream is = response.body().byteStream();
                            //change the stream to bimap
                            Bitmap bitmap = BitmapFactory.decodeStream(is);
                            //new a file to save bitmap
                            File file = new File("/sdcard/tang3.jpg");
                            file.createNewFile();
                            FileOutputStream fos = new FileOutputStream(file);
                            bitmap.compress(Bitmap.CompressFormat.JPEG,100,fos);
                            fos.close();
                        }
                    }
                });

            }
        }.start();
    }

get請求獲取文件

/**
     * get請求獲取文件
     *
     * @param view
     */
    public void getFile(View view) {

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://10.0.2.2:8080/0903/okhttp-3.4.1.jar")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()){
                    InputStream is = response.body().byteStream();
                    File file = new File("/sdcard/test.jar");
                    FileOutputStream fos = new FileOutputStream(file);
                    int len=0;
                    byte[] bytes = new byte[1024];
                    while ((len=is.read(bytes))!=-1){
                        fos.write(bytes,0,len);
                    }
                    is.close();
                    fos.close();
                }

            }
        });
    }

post請求登錄

/**
     * post請求登錄
     * @param view
     */
    public void postLogin(View view) {

        new Thread() {
            @Override
            public void run() {
                super.run();
                OkHttpClient client = new OkHttpClient();

                RequestBody formbody = new FormBody.Builder()
                        .add("name","jack")
                        .add("pwd","123")
                        .build();
                Request request = new Request.Builder()
                        .url("http://10.0.2.2:8080/0903/LoginServlet")
                        .post(formbody)
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (response.isSuccessful()){
                            Log.i(TAG, "result : "+response.body().string());
                        }else {
                            ...
                        }
                    }
                });
            }
        }.start();
    }

post請求上傳圖片

/**
     * post請求上傳圖片
     *
     * @param view
     */
    public void postImage(View view) {
        OkHttpClient client = new OkHttpClient();

        RequestBody fileBody = RequestBody
                .create(MediaType.parse("image/png"), new File("/sdcard/qiqiu.jpg"));
        RequestBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", "pic.jpg", fileBody)
                .build();

        Request request = new Request.Builder().url("http://10.0.2.2:8080/0903/UploadServlet")
                .post(body).build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()){
                   ...
                }else {
                   ...
                }
            }
        });

    }

post請求上傳文件

 /**
     * post請求上傳文件
     *
     * @param view
     */
    public void postFile(View view) {

        OkHttpClient client = new OkHttpClient();

        RequestBody fileBody = RequestBody
                .create(MediaType.parse("text/x-markdown; charset=utf-8"), new File("/sdcard/okHttp.md"));
        RequestBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", "ok.md", fileBody)
                .build();
        Request request = new Request.Builder()
                .url("http://10.0.2.2:8080/0903/UploadServlet")
                .post(body).build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()){
                    ...
                }else {
                    ...
                }
            }
        });
    }
發佈了19 篇原創文章 · 獲贊 18 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章