您好,登錄后才能下訂單哦!
httpclient通過post multipart/form-data 上傳文件
public static String httpClientUploadFile(String url, File file) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = "";
//每個post參數之間的分隔。隨意設定,只要不會和其他的字符串重復即可。
String boundary ="--------------4585696313564699";
try {
//文件名
String fileName = file.getName();
HttpPost httpPost = new HttpPost(url);
//設置請求頭
httpPost.setHeader("Content-Type","multipart/form-data; boundary="+boundary);
//HttpEntity builder
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//字符編碼
builder.setCharset(Charset.forName("UTF-8"));
//模擬瀏覽器
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//boundary
builder.setBoundary(boundary);
//multipart/form-data
builder.addPart("multipartFile",new FileBody(file));
// binary
// builder.addBinaryBody("name=\"multipartFile\"; filename=\"test.docx\"", new FileInputStream(file), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
//其他參數
builder.addTextBody("filename", fileName, ContentType.create("text/plain", Consts.UTF_8));
//HttpEntity
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
// 執行提交
HttpResponse response = httpClient.execute(httpPost);
//響應
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
// 將響應內容轉換為字符串
result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.err.println("result"+result);
return result;
}
//main 方法
public static void main(String[] args) {
httpClientUploadFile("http://127.0.0.1:8080/upload",new File("d:/test/test.docx"));
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。