14.3-Okhttp Retrofit 文件上传

上传接口:

文件上传接口:http://xxx/study/public/file_upload.php
传输类型 post
参数:(String key,String file);
key 上传文件的文件夹(自己随意传)
file 固定的"file"参数里面放上传文件的流内容

Okhttp 文件上传

//okhttp
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
  private void testOkhttp() {

        // 1-获取上传的文件路径
        String  path = Environment.getExternalStorageDirectory()+ File.separator+"xxx.png";
        //2-path-->File
        File file = new File(path);
        if (!file.exists()){
            Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
            return;
        }
        // 3-file--requestbody
        RequestBody fileRequestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);


        // 4-  requestbody--multipartBody
        MultipartBody multipartBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("key","320")
                .addFormDataPart("file",file.getName(),fileRequestBody)
                .build();

        //file --requestbody
//        new RequestBody(
        final Request request = new Request.Builder()
                .post(multipartBody)
                .url(uploadUrl)
                .build();
        // okhttp
        OkHttpClient okhttp = new OkHttpClient();
        okhttp.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                Log.d(TAG, "onFailure: "+e.getMessage());
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            mResult.setText(response.body().string());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });


    }

Retrofit 文件上传

网络请求的接口:

public interface ApiService {
    String mBaseUrl = "http://xxx.cn/";

    @Multipart
    @POST("study/public/file_upload.php")
    Observable<UploadBean> upload(@Part("key")RequestBody key, @Part MultipartBody.Part file);
}
  private void testRetrofit() {
        String path = Environment.getExternalStorageDirectory()+File.separator+"xxx.png";
        File file = new File(path);
        if (!file.exists()){
            Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
            return;
        }
        RequestBody fileRequestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);

        // key
        RequestBody keyRequestBody = RequestBody.create(MediaType.parse("application/text"), "321");

        // file
        MultipartBody.Part multipartBody = MultipartBody.Part.createFormData("file", file.getName(), fileRequestBody);


        Retrofit build = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl("http://yun918.cn/")
                .build();

        ApiService apiService = build.create(ApiService.class);
        retrofit2.Call<ResponseBody> responseBodyCall = apiService.uploadFile(keyRequestBody, multipartBody);
        responseBodyCall.enqueue(new retrofit2.Callback<ResponseBody>() {
            @Override
            public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {

                try {
                    mResult.setText(response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {

                Log.d(TAG, "onFailure: "+t.getMessage());
            }
        });


    }
发布了118 篇原创文章 · 获赞 16 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/chentaishan/article/details/104898272