OKhttp上传图片视频

 private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/jpg");

    private void updata(final File file, String filena) {


        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                // .addInterceptor(new TokenInterceptor())//添加获取token的拦截器
                .build();
        MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
        multipartBodyBuilder.setType(MultipartBody.FORM);
        //遍历map中所有参数到builder


        //遍历paths中所有图片绝对路径到builder,并约定key如“upload”作为后台接受多张图片的key
     
        multipartBodyBuilder.addFormDataPart("img", file.getName(), //img与后台约定好的参
        RequestBody.create(MEDIA_TYPE_PNG, file));

        //构建请求体
        RequestBody requestBody = multipartBodyBuilder.build();

        Request.Builder RequestBuilder = new Request.Builder();
        RequestBuilder.url(upUrl);// 添加URL地址
        RequestBuilder.post(requestBody);

        Request request = RequestBuilder.build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                Log.e(TAG, "onFailure: " + e.getMessage());

            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws 
          IOException {
                Log.e(TAG, response.protocol() + " " + response.code() + " " + 
           response.message());
                final String info = response.body().string();
             
                Log.e(TAG, info);
            }
        });

    }

你可能感兴趣的:(Android精华教程,okhttp,android)