美文网首页
【安卓相关】OkHttp之GET请求、POST请求、文件上传

【安卓相关】OkHttp之GET请求、POST请求、文件上传

作者: norkm | 来源:发表于2020-03-01 15:56 被阅读0次

    发送GET请求

            OkHttpClient OkHttpGet = new OkHttpClient();
            Request requestGet=new Request.Builder().url("https://www.norkm.com/").build();
            OkHttpGet.newCall(requestGet).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
    
                }
    
                @Override
                public void onResponse(Call call, Response response) {
                        /*
                        * 返回结果
                        * response.body().string()
                        * */
                }
            });
    

    发送POST请求

    相比GET请求也只是多了一个post方法,请求参数放置在FormBody.Builder 中。

            FormBody.Builder formBody = new FormBody.Builder();
            formBody.add("","");
    
            OkHttpClient okHttpPost =new OkHttpClient();
            Request requestPost = new Request.Builder().url("https://www.norkm.com/").post(formBody.build()).build();
            okHttpPost.newCall(requestPost).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
    
                }
    
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    /*
                     * 返回结果
                     * response.body().string()
                     * */
                }
            });
    

    发送POST请求,并携带文件上传

            OkHttpClient okHttpClientFile = new OkHttpClient();
            RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), new File("filePath"));
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("otherName","otherValue")
                    .addFormDataPart("file", "fileName", fileBody)
                    .build();
    
            Request uploadRequest = new Request.Builder().url("https://www.norkm.com/").post(requestBody).build();
    
            okHttpClientFile.newCall(uploadRequest).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
    
                }
    
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    /*
                     * 返回结果
                     * response.body().string()
                     * */
                }
            });
    

    相关文章

      网友评论

          本文标题:【安卓相关】OkHttp之GET请求、POST请求、文件上传

          本文链接:https://www.haomeiwen.com/subject/fceckhtx.html