httpclient中 RequestEntity和RequestBody区别

来源:互联网 发布:mac pictures 文件夹 编辑:程序博客网 时间:2024/06/06 09:38
有些情况会要求定制提交内容,例如一些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。


RequestEntity和RequestBody区别

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
packagecom.allcam.sys.thirdplat.kmc;
 
importjava.io.IOException;
importjava.io.InputStream;
 
importorg.apache.commons.httpclient.HttpClient;
importorg.apache.commons.httpclient.HttpStatus;
importorg.apache.commons.httpclient.methods.ByteArrayRequestEntity;
importorg.apache.commons.httpclient.methods.GetMethod;
importorg.apache.commons.httpclient.methods.InputStreamRequestEntity;
importorg.apache.commons.httpclient.methods.PostMethod;
importorg.apache.commons.httpclient.methods.RequestEntity;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
 
publicclass HttpRequestEntityUtils
{
    protectedstatic final int httpConnectionTimeOut = 30;
     
    protectedfinal static Logger log = LoggerFactory.getLogger(HttpRequestEntityUtils.class);
     
    publicstatic String post(String url, String params)
        throwsIOException
    {
        String body = null;
        HttpClient httpClient = null;
        PostMethod method = null;
         
        try
        {
            httpClient = newHttpClient();
             
            method = newPostMethod(url);
            // 链接超时30秒
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(1000* httpConnectionTimeOut);
            // 读取超时30秒
            httpClient.getHttpConnectionManager().getParams().setSoTimeout(1000* httpConnectionTimeOut); //
             
            log.info("create http post:" + url);
            RequestEntity requestEntity = newByteArrayRequestEntity(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);
            throwe;
        }
        catch(Exception e)
        {
            log.error("Exception", e);
            throwe;
        }
        finally
        {
            if(method != null)
            {
                method.releaseConnection();
            }
        }
        returnbody;
    }
     
    publicstatic String postPushStream(String url, InputStream inputStream)
        throwsIOException
    {
        String body = null;
        HttpClient httpClient = null;
        PostMethod method = null;
         
        try
        {
            httpClient = newHttpClient();
             
            method = newPostMethod(url);
            // 链接超时30秒
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(1000* httpConnectionTimeOut);
            // 读取超时30秒
            httpClient.getHttpConnectionManager().getParams().setSoTimeout(1000* httpConnectionTimeOut); //
             
            log.info("create http post:" + url);
            RequestEntity requestEntity = newInputStreamRequestEntity(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);
            throwe;
        }
        catch(Exception e)
        {
            log.error("Exception", e);
            throwe;
        }
        finally
        {
            if(method != null)
            {
                method.releaseConnection();
            }
        }
        returnbody;
    }
     
    publicstatic InputStream postGetStream(String url, String params)
        throwsIOException
    {
        InputStream body = null;
        HttpClient httpClient = null;
        PostMethod method = null;
        try
        {
            httpClient = newHttpClient();
             
            method = newPostMethod(url);
            // 链接超时30秒
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(1000* httpConnectionTimeOut);
            // 读取超时30秒
            httpClient.getHttpConnectionManager().getParams().setSoTimeout(1000* httpConnectionTimeOut); //
             
            log.info("create http post:" + url);
            RequestEntity requestEntity = newByteArrayRequestEntity(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);
            throwe;
        }
        catch(Exception e)
        {
            log.error("Exception", e);
            throwe;
        }
        finally
        {
            if(method != null)
            {
                method.releaseConnection();
            }
        }
        returnbody;
    }
     
    publicstatic String get(String url)
        throwsIOException
    {
        String body = null;
        HttpClient httpClient = null;
        GetMethod method = null;
         
        try
        {
            httpClient = newHttpClient();
             
            method = newGetMethod(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);
            throwe;
        }
        catch(Exception e)
        {
            log.error("Exception", e);
            throwe;
        }
        finally
        {
            if(method != null)
            {
                method.releaseConnection();
            }
        }
        returnbody;
    }
}

[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
packagecom.allcam.sys.thirdplat.kmc;
 
importjava.io.IOException;
importjava.io.UnsupportedEncodingException;
importjava.util.ArrayList;
importjava.util.List;
importjava.util.Map;
importjava.util.Set;
 
importorg.apache.http.HttpEntity;
importorg.apache.http.HttpResponse;
importorg.apache.http.NameValuePair;
importorg.apache.http.ParseException;
importorg.apache.http.client.ClientProtocolException;
importorg.apache.http.client.entity.UrlEncodedFormEntity;
importorg.apache.http.client.methods.HttpGet;
importorg.apache.http.client.methods.HttpPost;
importorg.apache.http.client.methods.HttpUriRequest;
importorg.apache.http.impl.client.DefaultHttpClient;
importorg.apache.http.message.BasicNameValuePair;
importorg.apache.http.protocol.HTTP;
importorg.apache.http.util.EntityUtils;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
 
publicclass HttpRequestBodyUtils
{
    protectedfinal static Logger log = LoggerFactory.getLogger(HttpRequestBodyUtils.class);
     
    publicstatic String post(String url, Map<String, String> params)
        throwsIOException
    {
        DefaultHttpClient httpclient = newDefaultHttpClient();
        String body = null;
         
        log.info("create http post:" + url);
        HttpPost post = postForm(url, params);
         
        body = invoke(httpclient, post);
         
        httpclient.getConnectionManager().shutdown();
         
        returnbody;
    }
     
    publicstatic String get(String url)
        throwsIOException
    {
        DefaultHttpClient httpclient = newDefaultHttpClient();
        String body = null;
         
        log.info("create http post:" + url);
        HttpGet get = newHttpGet(url);
        body = invoke(httpclient, get);
         
        httpclient.getConnectionManager().shutdown();
         
        returnbody;
    }
     
    privatestatic String invoke(DefaultHttpClient httpclient, HttpUriRequest httppost)
        throwsIOException
    {
         
        HttpResponse response = sendRequest(httpclient, httppost);
        String body = paseResponse(response);
         
        returnbody;
    }
     
    privatestatic String paseResponse(HttpResponse response)
        throwsIOException
    {
        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);
            throwe;
        }
        catch(IOException e)
        {
            log.error("IOException", e);
            throwe;
        }
        catch(Exception e)
        {
            log.error("Exception", e);
            throwe;
        }
        returnbody;
    }
     
    privatestatic HttpResponse sendRequest(DefaultHttpClient httpclient, HttpUriRequest httpost)
        throwsIOException
    {
        log.info("execute post...");
        HttpResponse response = null;
         
        try
        {
            response = httpclient.execute(httpost);
        }
        catch(ClientProtocolException e)
        {
            log.error("ClientProtocolException", e);
            throwe;
        }
        catch(IOException e)
        {
            log.error("IOException", e);
            throwe;
        }
        catch(Exception e)
        {
            log.error("Exception", e);
            throwe;
        }
        returnresponse;
    }
     
    privatestatic HttpPost postForm(String url, Map<String, String> params)
        throwsUnsupportedEncodingException
    {
         
        HttpPost httpost = newHttpPost(url);
        List<NameValuePair> nvps = newArrayList<NameValuePair>();
         
        Set<String> keySet = params.keySet();
        for(String key : keySet)
        {
            nvps.add(newBasicNameValuePair(key, params.get(key)));
        }
         
        try
        {
            log.info("set utf-8 form entity to httppost");
            httpost.setEntity(newUrlEncodedFormEntity(nvps, HTTP.UTF_8));
        }
        catch(UnsupportedEncodingException e)
        {
            log.error("UnsupportedEncodingException", e);
            throwe;
        }
        catch(Exception e)
        {
            log.error("Exception", e);
            throwe;
        }
        returnhttpost;
    }
}



原创粉丝点击