newmultipartentity php,HttpClient利用MultipartEntityBuilder取代MultipartEntity上传图片文件到服务器...

本文介绍使用HttpClient4.3之后的新文件上传方法MultipartEntityBuilder,并提供详细的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注意:在HttpClient4.3之后,原来的上传文件方法MultipartEntity已经不建议使用,现替换成新的httpmime下面的MultipartEntityBuilder。

需要添加httpclient-4.5.jar、httpmime-4.5.jar两个包

maven添加:

org.apache.httpcomponents

httpmime

4.5

org.apache.httpcomponents

httpclient

4.5

1

2

3

4

5

6

7

8

9

10

org.apache.httpcomponents

httpmime

4.5

org.apache.httpcomponents

httpclient

4.5

下面我们对比一下MultipartEntity和MultipartEntityBuilder的使用区别:

MultipartEntityBuilder:

//传入参数可以为file或者filePath,在此处做转换

File file = new File(filePath);

CloseableHttpClient httpClient = HttpClients.createDefault();

CloseableHttpResponse httpResponse = null;

HttpPost httppost = new HttpPost(url);

MultipartEntityBuilder builder = MultipartEntityBuilder.create();

//设置浏览器兼容模式

builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

//设置请求的编码格式

builder.setCharset(Consts.UTF_8);

builder.setContentType(ContentType.MULTIPART_FORM_DATA);

//添加文件

builder.addBinaryBody("file", file);

HttpEntity reqEntity = builder.build();

httppost.setEntity(reqEntity);

httpResponse = httpClient.execute(httppost);

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

//传入参数可以为file或者filePath,在此处做转换

Filefile=newFile(filePath);

CloseableHttpClienthttpClient=HttpClients.createDefault();

CloseableHttpResponsehttpResponse=null;

HttpPosthttppost=newHttpPost(url);

MultipartEntityBuilderbuilder=MultipartEntityBuilder.create();

//设置浏览器兼容模式

builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

//设置请求的编码格式

builder.setCharset(Consts.UTF_8);

builder.setContentType(ContentType.MULTIPART_FORM_DATA);

//添加文件

builder.addBinaryBody("file",file);

HttpEntityreqEntity=builder.build();

httppost.setEntity(reqEntity);

httpResponse=httpClient.execute(httppost);

MultipartEntity:

//传入参数可以为file或者filePath,在此处做转换

File file = new File(filePath);

CloseableHttpClient httpClient = HttpClients.createDefault();

CloseableHttpResponse httpResponse = null;

HttpPost httppost = new HttpPost(url);

FileBody filebody = new FileBody(file);

MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,

Charset.forName("UTF-8"));

entity.addPart("file", filebody);

httppost.setEntity(entity);

1

2

3

4

5

6

7

8

9

10

//传入参数可以为file或者filePath,在此处做转换

Filefile=newFile(filePath);

CloseableHttpClienthttpClient=HttpClients.createDefault();

CloseableHttpResponsehttpResponse=null;

HttpPosthttppost=newHttpPost(url);

FileBodyfilebody=newFileBody(file);

MultipartEntityentity=newMultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,null,

Charset.forName("UTF-8"));

entity.addPart("file",filebody);

httppost.setEntity(entity);

直接上替换后的测试代码:

package com.test.util;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import org.apache.http.Consts;

import org.apache.http.HttpEntity;

import org.apache.http.HttpStatus;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.entity.ContentType;

import org.apache.http.entity.mime.HttpMultipartMode;

import org.apache.http.entity.mime.MultipartEntityBuilder;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.util.EntityUtils;

import java.io.*;

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.Iterator;

import java.util.Map;

public class HttpPostUploadUtil {

/**

* @param args

*/

public static void main(String[] args) {

String filePath = "D:\\Test\\0.jpg";

String url = "http://127.0.0.1:8080/FastFds";

//调用上传方法

String backInfo = uploadPost(url, filePath);

if(StringUtils.isNotBlank(backInfo)){

//转json数据

JSONObject json = JSONObject.fromObject(backInfo);

if(!json.isEmpty()){

//数据处理

String value = json.getString("test");

System.out.println(value);

}

}

}

/**

* 上传图片/文件

* @param url

* @param filePath

* @return String 用于转json或者其他信息

*/

public static String uploadPost(String url, String filePath) {

String requestJson = "";

//传入参数可以为file或者filePath,在此处做转换

File file = new File(filePath);

CloseableHttpClient httpClient = HttpClients.createDefault();

CloseableHttpResponse httpResponse = null;

try {

HttpPost httppost = new HttpPost(url);

MultipartEntityBuilder builder = MultipartEntityBuilder.create();

//设置浏览器兼容模式

builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

//设置请求的编码格式

builder.setCharset(Consts.UTF_8);

builder.setContentType(ContentType.MULTIPART_FORM_DATA);

//添加文件

builder.addBinaryBody("file", file);

HttpEntity reqEntity = builder.build();

httppost.setEntity(reqEntity);

httpResponse = httpClient.execute(httppost);

int backCode = httpResponse.getStatusLine().getStatusCode();

if(backCode == HttpStatus.SC_OK){

HttpEntity httpEntity = httpResponse.getEntity();

byte[] json= EntityUtils.toByteArray(httpEntity);

requestJson = new String(json, "UTF-8");

//关闭流

EntityUtils.consume(httpEntity);

return requestJson;

}

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

//释放资源

try {

httpClient.close();

httpResponse.close();

} catch (IOException e) {

e.printStackTrace();

}

}

return null;

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

packagecom.test.util;

importnet.sf.json.JSONObject;

importorg.apache.commons.lang.StringUtils;

importorg.apache.http.Consts;

importorg.apache.http.HttpEntity;

importorg.apache.http.HttpStatus;

importorg.apache.http.client.ClientProtocolException;

importorg.apache.http.client.methods.CloseableHttpResponse;

importorg.apache.http.client.methods.HttpPost;

importorg.apache.http.entity.ContentType;

importorg.apache.http.entity.mime.HttpMultipartMode;

importorg.apache.http.entity.mime.MultipartEntityBuilder;

importorg.apache.http.impl.client.CloseableHttpClient;

importorg.apache.http.impl.client.HttpClients;

importorg.apache.http.util.EntityUtils;

importjava.io.*;

importjava.net.HttpURLConnection;

importjava.net.URL;

importjava.util.Iterator;

importjava.util.Map;

publicclassHttpPostUploadUtil{

/**

* @param args

*/

publicstaticvoidmain(String[]args){

StringfilePath="D:\\Test\\0.jpg";

Stringurl="http://127.0.0.1:8080/FastFds";

//调用上传方法

StringbackInfo=uploadPost(url,filePath);

if(StringUtils.isNotBlank(backInfo)){

//转json数据

JSONObjectjson=JSONObject.fromObject(backInfo);

if(!json.isEmpty()){

//数据处理

Stringvalue=json.getString("test");

System.out.println(value);

}

}

}

/**

* 上传图片/文件

* @param url

* @param filePath

* @return String 用于转json或者其他信息

*/

publicstaticStringuploadPost(Stringurl,StringfilePath){

StringrequestJson="";

//传入参数可以为file或者filePath,在此处做转换

Filefile=newFile(filePath);

CloseableHttpClienthttpClient=HttpClients.createDefault();

CloseableHttpResponsehttpResponse=null;

try{

HttpPosthttppost=newHttpPost(url);

MultipartEntityBuilderbuilder=MultipartEntityBuilder.create();

//设置浏览器兼容模式

builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

//设置请求的编码格式

builder.setCharset(Consts.UTF_8);

builder.setContentType(ContentType.MULTIPART_FORM_DATA);

//添加文件

builder.addBinaryBody("file",file);

HttpEntityreqEntity=builder.build();

httppost.setEntity(reqEntity);

httpResponse=httpClient.execute(httppost);

intbackCode=httpResponse.getStatusLine().getStatusCode();

if(backCode==HttpStatus.SC_OK){

HttpEntityhttpEntity=httpResponse.getEntity();

byte[]json=EntityUtils.toByteArray(httpEntity);

requestJson=newString(json,"UTF-8");

//关闭流

EntityUtils.consume(httpEntity);

returnrequestJson;

}

}catch(ClientProtocolExceptione){

e.printStackTrace();

}catch(IOExceptione){

e.printStackTrace();

}finally{

//释放资源

try{

httpClient.close();

httpResponse.close();

}catch(IOExceptione){

e.printStackTrace();

}

}

returnnull;

}

}

主要方法说明:

主要方法说明:

addBinaryBody、addPart、addTextBody方法用于添加要上传的数据,从上面的表格中可以发现用于添加数据的方法,都是key-value类型。所以在服务器端我们可以通过request.getPart("keyname")方式获取对应key的数据。也可以通过request.getParts()方式获取客户端通过以上三种方法提交所有数据。

1.通过addBinaryBody方法直接可以添加File、InputStream、byte[]类型的数据。

2.通过addPart方法只能添加ContentBody类型的数据,在org.apache.http.entity.mime.content包中已经提供了String、File以及InputStream对应的ContentBody类型的子类,如FileBody、InputStreamBody、StringBody,通过这些类我们可以将String、File以及InputStream类型的数据转换成ContentBody类型的数据。

3.通过addTextBody方法我们可以很方便的添加文本数据。、

MultipartEntityBuilder的API:

ead49458ec7d5234ee1edd7b192e89be.pngAPI一览

参考链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值