httpclient中 RequestEntity和RequestBody区别

有些情况会要求定制提交内容,例如一些ajax接口,
就要使用 RequestEntity
Java代码
RequestEntity requestEntity=new StringRequestEntity(text);   
  1. post.setRequestEntity(requestEntity);  


这个方法代替了以前直接设置Request body。
RequestEntity是一个接口,有很多实现:
ByteArrayRequestEntity, FileRequestEntity, InputStreamRequestEntity , MultipartRequestEntity, StringRequestEntity

基本上从名字上就可以直接看出功能,可以从字符串,流,文件,字节数组中产生request body。

还有更复杂的Multipart,就是夹杂文件和普通字段的提交。

比如提交一段xml,就可以直接用字符串提交来实现,模拟ajax , http+xml。


httpclient的poseMethod提交数据,httpclient3.1采用RequestEntity接口替代以前的RequestBody。 两种实现方式 供参考




[1].[文件] HttpRequestEntityUtils.java ~ 7KB    下载(8) 跳至 [1] [2]

?
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
package com.allcam.sys.thirdplat.kmc;
 
import java.io.IOException;
import java.io.InputStream;
 
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
public class HttpRequestEntityUtils
{
     protected static final int httpConnectionTimeOut = 30 ;
     
     protected final static Logger log = LoggerFactory.getLogger(HttpRequestEntityUtils. class );
     
     public static String post(String url, String params)
         throws IOException
     {
         String body = null ;
         HttpClient httpClient = null ;
         PostMethod method = null ;
         
         try
         {
             httpClient = new HttpClient();
             
             method = new PostMethod(url);
             // 链接超时30秒
             httpClient.getHttpConnectionManager().getParams().setConnectionTimeout( 1000 * httpConnectionTimeOut);
             // 读取超时30秒
             httpClient.getHttpConnectionManager().getParams().setSoTimeout( 1000 * httpConnectionTimeOut); //
             
             log.info( "create http post:" + url);
             RequestEntity requestEntity = new ByteArrayRequestEntity(params.getBytes( "UTF-8" ));
             
             method.setRequestEntity(requestEntity);
             if (method.getStatusCode() == HttpStatus.SC_OK)
             {
                 body = method.getResponseBodyAsString();
             }
             else
             {
                 log.error( "method.getStatusCode()" + method.getStatusCode());
             }
         }
         catch (IOException e)
         {
             log.error( "IOException" , e);
             throw e;
         }
         catch (Exception e)
         {
             log.error( "Exception" , e);
             throw e;
         }
         finally
         {
             if (method != null )
             {
                 method.releaseConnection();
             }
         }
         return body;
     }
     
     public static String postPushStream(String url, InputStream inputStream)
         throws IOException
     {
         String body = null ;
         HttpClient httpClient = null ;
         PostMethod method = null ;
         
         try
         {
             httpClient = new HttpClient();
             
             method = new PostMethod(url);
             // 链接超时30秒
             httpClient.getHttpConnectionManager().getParams().setConnectionTimeout( 1000 * httpConnectionTimeOut);
             // 读取超时30秒
             httpClient.getHttpConnectionManager().getParams().setSoTimeout( 1000 * httpConnectionTimeOut); //
             
             log.info( "create http post:" + url);
             RequestEntity requestEntity = new InputStreamRequestEntity(inputStream, "UTF-8" );
             
             method.setRequestEntity(requestEntity);
             if (method.getStatusCode() == HttpStatus.SC_OK)
             {
                 body = method.getResponseBodyAsString();
             }
             else
             {
                 log.error( "method.getStatusCode()" + method.getStatusCode());
             }
         }
         catch (IOException e)
         {
             log.error( "IOException" , e);
             throw e;
         }
         catch (Exception e)
         {
             log.error( "Exception" , e);
             throw e;
         }
         finally
         {
             if (method != null )
             {
                 method.releaseConnection();
             }
         }
         return body;
     }
     
     public static InputStream postGetStream(String url, String params)
         throws IOException
     {
         InputStream body = null ;
         HttpClient httpClient = null ;
         PostMethod method = null ;
         try
         {
             httpClient = new HttpClient();
             
             method = new PostMethod(url);
             // 链接超时30秒
             httpClient.getHttpConnectionManager().getParams().setConnectionTimeout( 1000 * httpConnectionTimeOut);
             // 读取超时30秒
             httpClient.getHttpConnectionManager().getParams().setSoTimeout( 1000 * httpConnectionTimeOut); //
             
             log.info( "create http post:" + url);
             RequestEntity requestEntity = new ByteArrayRequestEntity(params.getBytes( "UTF-8" ));
             
             method.setRequestEntity(requestEntity);
             if (method.getStatusCode() == HttpStatus.SC_OK)
             {
                 body = method.getResponseBodyAsStream();
             }
             else
             {
                 log.error( "method.getStatusCode()" + method.getStatusCode());
             }
         }
         catch (IOException e)
         {
             log.error( "IOException" , e);
             throw e;
         }
         catch (Exception e)
         {
             log.error( "Exception" , e);
             throw e;
         }
         finally
         {
             if (method != null )
             {
                 method.releaseConnection();
             }
         }
         return body;
     }
     
     public static String get(String url)
         throws IOException
     {
         String body = null ;
         HttpClient httpClient = null ;
         GetMethod method = null ;
         
         try
         {
             httpClient = new HttpClient();
             
             method = new GetMethod(url);
             // 链接超时30秒
             httpClient.getHttpConnectionManager().getParams().setConnectionTimeout( 1000 * httpConnectionTimeOut);
             // 读取超时30秒
             httpClient.getHttpConnectionManager().getParams().setSoTimeout( 1000 * httpConnectionTimeOut); //
             
             log.info( "create http get:" + url);
             if (method.getStatusCode() == HttpStatus.SC_OK)
             {
                 body = method.getResponseBodyAsString();
             }
             else
             {
                 log.error( "method.getStatusCode()" + method.getStatusCode());
             }
         }
         catch (IOException e)
         {
             log.error( "IOException" , e);
             throw e;
         }
         catch (Exception e)
         {
             log.error( "Exception" , e);
             throw e;
         }
         finally
         {
             if (method != null )
             {
                 method.releaseConnection();
             }
         }
         return body;
     }
}

[2].[文件] HttpRequestBodyUtils.java ~ 5KB    下载(4) 跳至 [1] [2]

?
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
 package com.allcam.sys.thirdplat.kmc;
 
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
public class HttpRequestBodyUtils
{
     protected final static Logger log = LoggerFactory.getLogger(HttpRequestBodyUtils. class );
     
     public static String post(String url, Map<String, String> params)
         throws IOException
     {
         DefaultHttpClient httpclient = new DefaultHttpClient();
         String body = null ;
         
         log.info( "create http post:" + url);
         HttpPost post = postForm(url, params);
         
         body = invoke(httpclient, post);
         
         httpclient.getConnectionManager().shutdown();
         
         return body;
     }
     
     public static String get(String url)
         throws IOException
     {
         DefaultHttpClient httpclient = new DefaultHttpClient();
         String body = null ;
         
         log.info( "create http post:" + url);
         HttpGet get = new HttpGet(url);
         body = invoke(httpclient, get);
         
         httpclient.getConnectionManager().shutdown();
         
         return body;
     }
     
     private static String invoke(DefaultHttpClient httpclient, HttpUriRequest httppost)
         throws IOException
     {
         
         HttpResponse response = sendRequest(httpclient, httppost);
         String body = paseResponse(response);
         
         return body;
     }
     
     private static String paseResponse(HttpResponse response)
         throws IOException
     {
         log.info( "get response from http server.." );
         HttpEntity entity = response.getEntity();
         
         log.info( "response status: " + response.getStatusLine());
         String charset = EntityUtils.getContentCharSet(entity);
         log.info(charset);
         
         String body = null ;
         try
         {
             body = EntityUtils.toString(entity);
             log.info(body);
         }
         catch (ParseException e)
         {
             log.error( "ParseException" , e);
             throw e;
         }
         catch (IOException e)
         {
             log.error( "IOException" , e);
             throw e;
         }
         catch (Exception e)
         {
             log.error( "Exception" , e);
             throw e;
         }
         return body;
     }
     
     private static HttpResponse sendRequest(DefaultHttpClient httpclient, HttpUriRequest httpost)
         throws IOException
     {
         log.info( "execute post..." );
         HttpResponse response = null ;
         
         try
         {
             response = httpclient.execute(httpost);
         }
         catch (ClientProtocolException e)
         {
             log.error( "ClientProtocolException" , e);
             throw e;
         }
         catch (IOException e)
         {
             log.error( "IOException" , e);
             throw e;
         }
         catch (Exception e)
         {
             log.error( "Exception" , e);
             throw e;
         }
         return response;
     }
     
     private static HttpPost postForm(String url, Map<String, String> params)
         throws UnsupportedEncodingException
     {
         
         HttpPost httpost = new HttpPost(url);
         List<NameValuePair> nvps = new ArrayList<NameValuePair>();
         
         Set<String> keySet = params.keySet();
         for (String key : keySet)
         {
             nvps.add( new BasicNameValuePair(key, params.get(key)));
         }
         
         try
         {
             log.info( "set utf-8 form entity to httppost" );
             httpost.setEntity( new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
         }
         catch (UnsupportedEncodingException e)
         {
             log.error( "UnsupportedEncodingException" , e);
             throw e;
         }
         catch (Exception e)
         {
             log.error( "Exception" , e);
             throw e;
         }
         return httpost;
     }
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: HttpClient发送POST请求时,可以通过设置请求体(body)来传递参数或数据。具体步骤如下: 1. 创建HttpClient对象 ``` CloseableHttpClient httpClient = HttpClients.createDefault(); ``` 2. 创建HttpPost对象,并设置请求URL ``` HttpPost httpPost = new HttpPost("http://example.com/api"); ``` 3. 创建请求体(body),并设置请求头 ``` String requestBody = "{\"name\":\"John\", \"age\":30}"; StringEntity entity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); httpPost.setEntity(entity); ``` 4. 发送请求,并获取响应 ``` CloseableHttpResponse response = httpClient.execute(httpPost); ``` 5. 处理响应 ``` HttpEntity responseEntity = response.getEntity(); String responseBody = EntityUtils.toString(responseEntity); System.out.println(responseBody); ``` 以上就是使用HttpClient发送POST请求并设置请求体的基本步骤。需要注意的是,请求体的格式和内容应该根据API文档或接口规范进行设置。 ### 回答2: HttpClient是一个开源的Java HTTP客户端工具包,可以用来发送HTTP请求。在发送POST请求时,我们需要往请求体添加参数,这就需要用到HttpClient发送POST请求bodyHttpClient发送POST请求有两种方法:使用NameValuePair键值对和使用字符串。两种方法的使用取决于请求的内容。如果是简单的键值对,可以使用NameValuePair键值对;如果请求内容较为复杂,需要包含一些json格式的数据,那么就需要使用字符串的方式。 使用NameValuePair键值对发送POST请求: NameValuePair是一种存储参数的方法,我们可以通过NameValuePair将参数键值对添加到请求体,代码示例如下: ``` // 创建一个 HttpClient 客户端 CloseableHttpClient httpClient = HttpClients.createDefault(); // 设置请求地址 HttpPost httpPost = new HttpPost("http://localhost:8080/test"); // 设置请求头部信息 httpPost.setHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8"); // 设置请求参数 List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("username", "admin")); params.add(new BasicNameValuePair("password", "admin")); // 设置请求体 httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); // 执行请求并获取响应 CloseableHttpResponse response = httpClient.execute(httpPost); // 获取响应消息实体 HttpEntity responseEntity = response.getEntity(); // 打印响应内容 System.out.println(EntityUtils.toString(responseEntity)); // 关闭响应对象 response.close(); // 关闭客户端对象 httpClient.close(); ``` 使用字符串发送POST请求: 发送POST请求时,我们可以将请求体需要传递的json对象转换成字符串形式,然后将该字符串作为请求体发送。代码示例如下: ``` // 创建一个 HttpClient 客户端 CloseableHttpClient client = HttpClients.createDefault(); // 设置请求地址 HttpPost post = new HttpPost("http://localhost:8080/test"); // 设置请求头部信息 post.setHeader("Content-Type", "application/json; charset=utf-8"); // 设置请求体 StringEntity entity = new StringEntity("{\"username\":\"admin\",\"password\":\"admin\"}", "UTF-8"); post.setEntity(entity); // 执行请求并获取响应 CloseableHttpResponse response = client.execute(post); // 获取响应消息实体 HttpEntity responseEntity = response.getEntity(); // 打印响应内容 System.out.println(EntityUtils.toString(responseEntity)); // 关闭响应对象 response.close(); // 关闭客户端对象 client.close(); ``` 以上就是使用HttpClient发送POST请求body的方法,通过该方法可以方便地处理POST请求,以此实现数据的传输和接收。需要注意的是,在发送POST请求的同时需注意设置请求头和请求体的信息,以便正确地传输请求。 ### 回答3: HttpClient是Java语言一个方便的开源HTTP客户端库,用于https请求。它能够实现快速,自由,轻松的实现HTTP请求,可以支持Get、Post、Put、Delete、Head等方法。而POST请求常用于客户端提交数据给服务器端,接着进行处理,故HttpClient发送POST请求是非常重要的。 使用HttpClient发送POST请求主要涉及以下几个方面: 1.构建HttpClient对象:可通过HttpClients.createDefault()方法来创建一个默认的HttpClient实例。 2.构建HttpPost对象:可通过HttpPost(String url)方法来构建一个HttpPost请求体实例。 3.构建Post请求参数:至少需要设置请求体的请求参数。 4.设置请求头:可通过setHeader()方法增加请求头信息,如设置Content-Type和User-Agent等信息。 5.设置请求体:可通过setEntity()方法设置请求体,向服务端传递数据,请求参数类型可为String、ByteArrayEntity、InputStreamEntity、FileEntity等。 6.发送Post请求:可通过提交HttpPost请求来实现向服务端发送POST请求。 以下是HttpClient发送Post请求代码示例: ``` try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost("http://www.xxx.com/post"); httpPost.setHeader("Content-Type", "application/json"); StringEntity stringEntity = new StringEntity("{\"name\":\"test\", \"age\":18}"); httpPost.setEntity(stringEntity); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); String responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8"); System.out.println("responseContent: " + responseContent); } catch (Exception e) { e.printStackTrace(); } ``` 该示例通过HttpPost(String url)方法构建HttpPost请求实例,并设置请求头信息,如Content-Type和User-Agent等。然后通过StringEntity(String str)方法将JSON格式的请求参数字符串设置到请求体。最后通过httpClient.execute(httpPost)方法提交HttpPost请求,接收服务端返回的HttpResponse响应实例,并通过EntityUtils.toString()方法获取响应内容。 总结:HttpClient发送POST请求主要是通过构建HttpPost实例对象,设置请求头和请求体参数,最后提交HttpPost请求向服务器发送POST请求,可以方便的实现与服务端的数据交互。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值