大家好,又见面了,我是你们的朋友全栈君。
gradle项目
compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.3'
maven项目
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
上传
HttpClient HTTP_CLIENT = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://localhost/file/upload");
try {
final MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
multipartEntity.setCharset(Charset.forName("utf-8"));
multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//for (String[] nameValue : datas) {//普通data字段
// multipartEntity.addPart(nameValue[0], new StringBody(nameValue[1], ContentType.APPLICATION_JSON));
//}
multipartEntity.addBinaryBody("file", file);//文件字段
httpPost.setEntity(multipartEntity.build());
//httpPost.setHeader("token", token);//设置请求头
String result = EntityUtils.toString(HTTP_CLIENT.execute(httpPost).getEntity());
} catch (IOException e) {
e.printStackTrace();
}
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/163253.html原文链接:https://javaforall.cn