上传图片到接口上

compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'com.squareup.okio:okio:1.5.0'
compile 'com.google.code.gson:gson:2.2.4'

接口为  private String set="https://www.zhaoapi.cn/file/upload?uid=10134";


//第一个参数为url路径  第二个为图片的路径  第三个为图片的名字
 public static void uploadPic(String url, File file, String fileName) {
    //创建OkHttpClient请求对象

    OkHttpClient okHttpClient = new OkHttpClient();
    //创建RequestBody 封装file参数
    RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
    //创建RequestBody 设置类型等
    RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", fileName, fileBody).build();
    //创建Request
    Request request = new Request.Builder().url(url).post(requestBody).build();

    //得到Call
    Call call = okHttpClient.newCall(request);
    //执行请求
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.d("失败", "onResponse: 很不高兴");
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            //上传成功回调 目前不需要处理
            Log.d("成功", "onResponse: 开心");
        }
    });

}

你可能感兴趣的:(上传图片到接口上)