okHttp上传文件

OkHttpClient okHttpClient =new OkHttpClient();

MediaType parse = MediaType.parse("application/octet-stream");//上传的数据类型

File file =new File("/storage/sdcard0/Pictures/music1.mp3");

if (file !=null) {

RequestBody requestBody = RequestBody.create(parse, file);

    MultipartBody build =new MultipartBody.Builder()

.addFormDataPart("file", file.getName(), requestBody)

.addFormDataPart("key", "ccc")

.setType(MultipartBody.FORM)

.build();

    Request request =new Request.Builder()


.url("http://yun918.cn/study/public/file_upload.php")

.post(build)

.build();

    okHttpClient.newCall(request).enqueue(new Callback() {

@Override

        public void onFailure(Call call, IOException e) {

Log.i("失败", "onFailure: " +"失败");

        }

@Override

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

String s = response.body().string();

            Log.i("aa", "onResponse: " + s);

        }

});

}

你可能感兴趣的:(okHttp上传文件)