okhttp-上传文件

2017-01-01 10:46
  • 导入okhttp-3.4.1.jar
  • 导入okio-1.9.0.jar

  • 直接上代码

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
//通过“addFormDataPart”可以添加多个上传的文件。
public  class OkHttpCallBackWrap {
    public void post(String url) throws IOException{
                File file = new File("D:/app/dgm/3.mp4");
                RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
                RequestBody requestBody = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM) 
                        .addFormDataPart("application/octet-stream", "1.mp4", fileBody)
                        .build();
                Request request = new Request.Builder()
                        .url(url)
                        .post(requestBody)
                        .build();

                final okhttp3.OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
                OkHttpClient okHttpClient  = httpBuilder
                        //设置超时
                        .connectTimeout(100, TimeUnit.SECONDS)
                        .writeTimeout(150, TimeUnit.SECONDS)
                        .build();
                okHttpClient.newCall(request).enqueue(new Callback() {

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        System.out.println(response.body().string());
                    }

                    @Override
                    public void onFailure(Call arg0, IOException e) {
                        // TODO Auto-generated method stub
                        System.out.println(e.toString());

                    }

                });
            }
        }