httpClient4.3之後上傳文件使用MultipartEntityBuilder
- 設置上傳模式setMode(),其中mode主要有BROWSER_COMPATIBLE,RFC6532,STRICT三種,默認值是STRICT。
創建MultipartEntityBuilder對象,並添加需要上傳的數據:利用MultipartEntityBuilder.create()來創建對象; addBinaryBody:以二進制的形式添加數據,可以添加File、InputStream、byte[]類型的數據。addBinaryBody(String name, File file, ContentType contentType, String filename)
addBinaryBody(String name, InputStream stream, ContentType contentType, String filename) addTextBody:添加文本數據
addPart:以Key/Value的形式添加ContentBody類型的數據
addPart(String name, ContentBody contentBody)
- 更多函數可以參考:https://hc.apache.org/httpcomponents-client-ga/httpmime/apidocs/org/apache/http/entity/mime/MultipartEntityBuilder.html。在GACHA API中,主要是上傳圖片,所以在測試中選用了addBinaryBody。其中,第一個參數name的值,是服務器已經定義好的,服務器會根據這個字段來讀取我們上傳的文件流,不匹配則會報錯。關於contentType,可以參考:http://tool.oschina.net/commons,不同文件擴展名所對應的類型。而file/stream和fileName,就是我們所要上傳文件的信息。當用瀏覽器的開發者工具查看API請求時,我們會看到這些/參數基本位於API請求中的 Request Payload字段。
接口測試之文件上傳——MultipartEntityBuilder - fengchao - fengchao2468的博客
3. 然後是利用build()方法創建一個HttpEntity對象;
最後將HttpEntity對象添加到指定的URL上,採用HttpPost的setEntity的方法;
最後的最後,就是調用HttpClient對象發送請求,並獲取服務器的響應
6.具體代碼
HttpPost httppost = new HttpPost(url);
final HttpEntity entity = makeMultipartEntity(params, files);
httppost.addHeader(entity.getContentType());
//httppost.addHeader(entity.getContentEncoding()); //null
httppost.setEntity(entity);
HttpResponse response = getHttpClient().execute(httppost);
private static HttpClient mClient;
private static HttpClient getHttpClient() {
if(mClient == null) {
//if(Build.VERSION.SDK_INT >= 9); //將不走本類的Case,基於HttpURLConnection
if(Build.VERSION.SDK_INT >= 8) {
mClient = AndroidHttpClient.newInstance(getUserAgent());
}else {
mClient = new DefaultHttpClient();
}
}
return mClient;
}`
public static HttpEntity makeMultipartEntity(List<NameValuePair> params, final Map<String, File> files) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); //如果有SocketTimeoutException等情況,可修改這個枚舉
//builder.setCharset(Charset.forName("UTF-8"));
//不要用這個,會導致服務端接收不到參數
if (params != null && params.size() > 0) {
for (NameValuePair p : params) {
builder.addTextBody(p.getName(), p.getValue(), ContentType.TEXT_PLAIN.withCharset("UTF-8"));
}
}
if (files != null && files.size() > 0) {
Set<Entry<String, File>> entries = files.entrySet();
for (Entry<String, File> entry : entries) {
builder.addPart(entry.getKey(), new FileBody(entry.getValue()));
}
}
return builder.build();
}