【httpclient-4.3.1.jar】httpclient发送get、post请求以及携带数据上传文件

 

 

 

 

工具类封装如下:

  1 package cn.qlq.utils;
  2 
  3 import java.io.File;
  4 import java.io.IOException;
  5 import java.nio.charset.StandardCharsets;
  6 import java.util.ArrayList;
  7 import java.util.HashMap;
  8 import java.util.Iterator;
  9 import java.util.List;
 10 import java.util.Map;
 11 import java.util.Map.Entry;
 12 import java.util.Set;
 13 
 14 import org.apache.commons.io.IOUtils;
 15 import org.apache.http.HttpEntity;
 16 import org.apache.http.HttpStatus;
 17 import org.apache.http.NameValuePair;
 18 import org.apache.http.ParseException;
 19 import org.apache.http.client.entity.UrlEncodedFormEntity;
 20 import org.apache.http.client.methods.CloseableHttpResponse;
 21 import org.apache.http.client.methods.HttpGet;
 22 import org.apache.http.client.methods.HttpPost;
 23 import org.apache.http.entity.ContentType;
 24 import org.apache.http.entity.StringEntity;
 25 import org.apache.http.entity.mime.HttpMultipartMode;
 26 import org.apache.http.entity.mime.MultipartEntityBuilder;
 27 import org.apache.http.entity.mime.content.FileBody;
 28 import org.apache.http.impl.client.CloseableHttpClient;
 29 import org.apache.http.impl.client.HttpClientBuilder;
 30 import org.apache.http.message.BasicNameValuePair;
 31 import org.apache.http.protocol.HTTP;
 32 import org.apache.http.util.EntityUtils;
 33 import org.slf4j.Logger;
 34 import org.slf4j.LoggerFactory;
 35 
 36 /**
 37  * http工具类的使用
 38  * 
 39  * @author Administrator
 40  *
 41  */
 42 public class HttpUtils {
 43 
 44     private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);
 45 
 46     /**
 47      * get请求
 48      * 
 49      * @return
 50      */
 51     public static String doGet(String url) {
 52         CloseableHttpClient client = null;
 53         CloseableHttpResponse response = null;
 54         try {
 55             // 定义HttpClient
 56             client = HttpClientBuilder.create().build();
 57             // 发送get请求
 58             HttpGet request = new HttpGet(url);
 59             // 执行请求
 60             response = client.execute(request);
 61 
 62             return getResponseResult(response);
 63         } catch (Exception e) {
 64             logger.error("execute error,url: {}", url, e);
 65         } finally {
 66             IOUtils.closeQuietly(response);
 67             IOUtils.closeQuietly(client);
 68         }
 69 
 70         return "";
 71     }
 72 
 73     /**
 74      * get请求携带参数
 75      * 
 76      * @return
 77      */
 78     public static String doGetWithParams(String url, Map<String, String> params) {
 79         CloseableHttpClient client = null;
 80         CloseableHttpResponse response = null;
 81         try {
 82             // 定义HttpClient
 83             client = HttpClientBuilder.create().build();
 84 
 85             // 1.转化参数
 86             if (params != null && params.size() > 0) {
 87                 List<NameValuePair> nvps = new ArrayList<NameValuePair>();
 88                 for (Iterator<String> iter = params.keySet().iterator(); iter.hasNext();) {
 89                     String name = iter.next();
 90                     String value = params.get(name);
 91                     nvps.add(new BasicNameValuePair(name, value));
 92                 }
 93                 String paramsStr = EntityUtils.toString(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
 94                 url += "?" + paramsStr;
 95             }
 96 
 97             HttpGet request = new HttpGet(url);
 98             response = client.execute(request);
 99 
100             return getResponseResult(response);
101         } catch (IOException e) {
102             logger.error("execute error,url: {}", url, e);
103         } finally {
104             IOUtils.closeQuietly(response);
105             IOUtils.closeQuietly(client);
106         }
107 
108         return "";
109     }
110 
111     public static String doPost(String url, Map<String, String> params) {
112         CloseableHttpClient client = null;
113         CloseableHttpResponse response = null;
114         try {
115             // 定义HttpClient
116             client = HttpClientBuilder.create().build();
117             HttpPost request = new HttpPost(url);
118 
119             // 1.转化参数
120             if (params != null && params.size() > 0) {
121                 List<NameValuePair> nvps = new ArrayList<NameValuePair>();
122                 for (Iterator<String> iter = params.keySet().iterator(); iter.hasNext();) {
123                     String name = iter.next();
124                     String value = params.get(name);
125                     nvps.add(new BasicNameValuePair(name, value));
126                 }
127                 request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
128             }
129 
130             response = client.execute(request);
131             return getResponseResult(response);
132         } catch (IOException e) {
133             logger.error("execute error,url: {}", url, e);
134         } finally {
135             IOUtils.closeQuietly(response);
136             IOUtils.closeQuietly(client);
137         }
138 
139         return "";
140     }
141 
142     public static String doPost(String url, String params) {
143         return doPost(url, params, false);
144     }
145 
146     /**
147      * post请求(用于请求json格式的参数)
148      * 
149      * @param url
150      * @param params
151      * @param isJsonData
152      * @return
153      */
154     public static String doPost(String url, String params, boolean isJsonData) {
155         CloseableHttpClient client = null;
156         CloseableHttpResponse response = null;
157         try {
158             // 定义HttpClient
159             client = HttpClientBuilder.create().build();
160 
161             HttpPost request = new HttpPost(url);
162             StringEntity entity = new StringEntity(params, HTTP.UTF_8);
163             request.setEntity(entity);
164 
165             if (isJsonData) {
166                 request.setHeader("Accept", "application/json");
167                 request.setHeader("Content-Type", "application/json");
168             }
169 
170             response = client.execute(request);
171 
172             return getResponseResult(response);
173         } catch (IOException e) {
174             logger.error("execute error,url: {}", url, e);
175         } finally {
176             IOUtils.closeQuietly(response);
177             IOUtils.closeQuietly(client);
178         }
179 
180         return "";
181     }
182 
183     /**
184      * 上传文件携带参数发送请求
185      * 
186      * @param url
187      *            URL
188      * @param fileName
189      *            neme,相当于input的name
190      * @param filePath
191      *            本地路径
192      * @param params
193      *            参数
194      * @return
195      */
196     public static String doPostWithFile(String url, String fileName, String filePath, Map<String, String> params) {
197         CloseableHttpClient httpclient = HttpClientBuilder.create().build();
198         CloseableHttpResponse response = null;
199         try {
200             MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
201 
202             // 上传文件,如果不需要上传文件注掉此行
203             multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE).addPart(fileName,
204                     new FileBody(new File(filePath)));
205 
206             if (params != null && params.size() > 0) {
207                 Set<Entry<String, String>> entrySet = params.entrySet();
208                 for (Entry<String, String> entry : entrySet) {
209                     multipartEntityBuilder.addTextBody(entry.getKey(), entry.getValue(),
210                             ContentType.create(HTTP.PLAIN_TEXT_TYPE, StandardCharsets.UTF_8));
211                 }
212             }
213 
214             HttpEntity httpEntity = multipartEntityBuilder.build();
215 
216             HttpPost httppost = new HttpPost(url);
217             httppost.setEntity(httpEntity);
218 
219             response = httpclient.execute(httppost);
220             return getResponseResult(response);
221         } catch (Exception e) {
222             logger.error("execute error,url: {}", url, e);
223         } finally {
224             IOUtils.closeQuietly(response);
225             IOUtils.closeQuietly(httpclient);
226         }
227 
228         return "";
229     }
230 
231     private static String getResponseResult(CloseableHttpResponse response) throws ParseException, IOException {
232         /** 请求发送成功,并得到响应 **/
233         if (response != null) {
234             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
235                 return EntityUtils.toString(response.getEntity(), "utf-8");
236             } else {
237                 logger.error("getResponseResult code error, code: {}", response.getStatusLine().getStatusCode());
238             }
239         }
240 
241         return "";
242     }
243 }

上述代码支持application/json数据的传送。post方法的isJsonData 为true即在请求头部加上application/json。

测试:

 1 public static void main(String[] args) {
 2         String doGet = doGet("http://localhost:8088//weixin/test/test.html?name=zs&age=25");
 3         System.out.println(doGet);
 4 
 5         Map<String, String> map = new HashMap<String, String>();
 6         map.put("xx", "xxx");
 7         String doGetWithParams = doGetWithParams("http://localhost:8088//weixin/test/test.html", map);
 8         System.out.println(doGetWithParams);
 9 
10         String doPost = doPost("http://localhost:8088//weixin/test/test.html?name=zs&age=25", "");
11         System.out.println(doPost);
12 
13         String doPost2 = doPost("http://localhost:8088//weixin/test/test.html?name=zs&age=25", map);
14         System.out.println(doPost2);
15     }

 

posted @ 2020-12-08 10:57  HelloWorld102  阅读(299)  评论(0编辑  收藏  举报