安卓Okhttp的基本操作

後臺請求文檔  https://github.com/TrillGates/SOBAndroidMiniWeb

學習使用,實際工作要封裝起來,線程管理起來

基本get請求

public void getRequest(View view) {
        //客戶端
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10000, TimeUnit.MILLISECONDS)
                .build();

        //創建請求內容
        final Request request = new Request.Builder()
                .get()
                .url("http://10.0.2.2:9102/get/text")
                .build();

        //用Client去創建請求任務
        Call call = client.newCall(request);

        //異步請求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.d(TAG, "onFailure: " + e.toString());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String string = response.body().string();
                Log.d(TAG, "onResponse: " + string);
                int code = response.code();
                Log.d(TAG, "onResponse: " + code);
            }
        });
    }

帶參數的get請求

public void getParameter(View view) {

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10000, TimeUnit.MILLISECONDS)
                .build();

        Map<String, String> map = new HashMap<>();
        map.put("keyword", "key");
        map.put("page", "12");
        map.put("order", "0");

        StringBuilder sb = new StringBuilder();
        sb.append("?");
        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> next = iterator.next();
            sb.append(next.getKey());
            sb.append("=");
            sb.append(next.getValue());
            if (iterator.hasNext()) {
                sb.append("&");
            }
        }
        String s = sb.toString();

        Log.e(TAG, "----" + s);
        Request request = new Request.Builder()
                .url(base_url1 + "/get/param" + s)
                .get()
                .build();


        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e(TAG, "onFailure: " + e.toString());
            }

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

    }

post請求方法帶參數

public void postParameter(View view) {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10000,TimeUnit.MILLISECONDS)
                .build();


        FormBody.Builder builder = new FormBody.Builder();

        RequestBody requestBody = builder
                .add("userName","123")
                .add("password","123456")
                .build();

        Request request = new Request.Builder()
                .url(base_url1 + "/login")
                .post(requestBody)
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e(TAG, "onFailure: " + e.toString());
            }

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


    }

提交評論

public void postComment(View view) {
        //客戶端
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10000, TimeUnit.MILLISECONDS)
                .build();

        //提交內容
        CommandItem commandItem = new CommandItem("123456", "hello!");
        Gson gson = new Gson();
        String jsonstr = gson.toJson(commandItem);

        MediaType mediaType = MediaType.parse("application/json");

        RequestBody requestBody = RequestBody.create(jsonstr, mediaType);

        final Request request = new Request.Builder()
                .url(base_url + "/post/comment")
                .post(requestBody)
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e(TAG, "onFailure: " + e.toString());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                int code = response.code();
                Log.e(TAG, "onResponse: " + code);
                if (code == HTTP_OK) {
                    ResponseBody body = response.body();
                    Log.e(TAG, "onResponse: " + body.string());
                }
            }
        });
    }

上傳單文件

public void postFile(View view) {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10000,TimeUnit.MILLISECONDS)
                .build();

        File file = new File("/storage/self/primary/Download/u=2604811881,2055398559&fm=173&app=49&f=JPEG.jpg");
        MediaType mediaType = MediaType.parse("image/png");
        RequestBody filebody = RequestBody.create(file,mediaType);

        RequestBody requestBody = new MultipartBody.Builder()
                .addFormDataPart("file",file.getName(),filebody)
                .build();

        Request request = new Request.Builder()
                .url(base_url + "/file/upload")
                .post(requestBody)
                .build();

        Call call = client.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e(TAG, "onFailure: "+e.toString() );
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                int code = response.code();
                Log.e(TAG, "onResponse: "+code);
                if (code == HTTP_OK){

                    Log.e(TAG, "onResponse: "+response.body().string() );
                }
            }
        });
    }

下載文件

public void DownloadFiles(View view) {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10000,TimeUnit.MILLISECONDS)
                .build();

        Request request = new Request.Builder()
                .url(base_url1+"/download/15")
                .get()
                .build();

        final Call call = client.newCall(request);
        new Thread(new Runnable() {
            @Override
            public void run() {
                InputStream inputStream = null;
                FileOutputStream fos = null;
                try {
                    Response execute = call.execute();
                    Headers headers = execute.headers();
                    for (int i = 0; i < headers.size(); i++) {
                        Log.e(TAG, "run: "+headers.name(i) + " "+headers.value(i));
                    }

                    String contentType = headers.get("Content-disposition");
                    String fileName = contentType.replace("attachment; filename=", "");
                    File outFile = new File(OkhttpActivity.this.getExternalFilesDir(Environment.DIRECTORY_PICTURES)+ File.separator+fileName);
                    if (outFile.getParentFile().exists()) {
                        outFile.mkdirs();
                    }
                    if(!outFile.exists()){
                        outFile.createNewFile();
                    }

                    fos = new FileOutputStream(outFile);

                    if (execute.body()!=null) {
                        inputStream = execute.body().byteStream();
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = inputStream.read(buffer,0,buffer.length))!=-1){
                            fos.write(buffer,0,len);
                        }
                        fos.flush();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    if (inputStream!=null) {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    if (fos!=null) {
                        try {
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        }).start();

    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章