在使用okhttp3 进行文件上传的时候,我们会使用多种类型表单的格式进行上传,因为我们不仅要上传文件File,还会附带一些参数过去。
下面就是okhttp上传的代码
try {
//补全请求地址
String requestUrl = String.format("%s%s", HttpRequestBase.DEFAULT_HTTP_HOST_ADDRESS, url);
LogUtils.d(TAG , "requestUrl == " + requestUrl);
MultipartBody.Builder builder = new MultipartBody.Builder();
//设置类型
builder.setType(MultipartBody.FORM);
//追加参数
for (String key : paramsMap.keySet()) {
Object object = paramsMap.get(key);
if (!(object instanceof File)) {
builder.addFormDataPart(key, object.toString());
} else {
File file = (File) object;
builder.addFormDataPart(key, file.getName(), createProgressRequestBody(MEDIA_OBJECT_STREAM, file, callback));
}
}
//创建RequestBody
RequestBody body = builder.build();
//创建Request
final Request request = new Request.Builder().url(requestUrl).post(body).build();
//单独设置参数 比如读取超时时间
final Call call = mOkHttpClient.newBuilder().writeTimeout(50, TimeUnit.SECONDS).build().newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
LogUtils.e(TAG, e.toString());
sendFailedStringCallback(call.request(), e, callback);
}
@Override
public void onResponse(Call call, Response response) {
try {
final String string = response.body().string();
LogUtils.d(TAG , " response body " + string);
if (callback.mType == String.class) {
sendSuccessResultCallback(string, callback);
} else {
Object o = mGson.fromJson(string, callback.mType);
sendSuccessResultCallback(o, callback);
}
} catch (IOException e) {
sendFailedStringCallback(response.request(), e, callback);
} catch (com.google.gson.JsonParseException e)//Json解析的错误
{
sendFailedStringCallback(response.request(), e, callback);
}
}
});
} catch (Exception e) {
LogUtils.e(TAG, e.toString());
}
public static final MediaType FORM = MediaType.parse("multipart/form-data");
从上面可以看出,有个boundary 分隔符,是用来进行内容的分割如文件内容和文本内容。这个boundary 的生成
public Builder() {
this(UUID.randomUUID().toString());
}
public Builder(String boundary) {
this.boundary = ByteString.encodeUtf8(boundary);
}
生成一个唯一的Id。
public static Part createFormData(String name, String filename, RequestBody body) {
if (name == null) {
throw new NullPointerException("name == null");
}
StringBuilder disposition = new StringBuilder("form-data; name=");
appendQuotedString(disposition, name);
if (filename != null) {
disposition.append("; filename=");
appendQuotedString(disposition, filename);
}
return create(Headers.of("Content-Disposition", disposition.toString()), body);
}
这段代码就是生成multipart/form-data 请求体,name 是server端对应的字段,filename 是文件的名称,content-type 是 octet-stream 表明他就是一个字节流,浏览器默认处理字节流的方式就是下载。content-type 这个类型需要与server端的配置是一致的,否则不能成功。
下面是部分上传类型
'image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg', 'image/png','application/msword','application/vnd.ms-excel',
'image/bmp','text/plain','application/octet-stream','image/x-png','application/x-shockwave-flash','audio/mpeg','audio/x-ms-wma',
'application/x-zip-compressed'