Http的Post/Get请求示例

悠悠 2022-04-15 05:27 856阅读 0赞

一、所需要的jar包

httpclient-4.5.jar

httpcore-4.4.1.jar

httpmime-4.5.jar

二、实例

  1. package cn.tzz.apache.httpclient;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.net.URL;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. import java.util.Map;
  8. import org.apache.http.HttpEntity;
  9. import org.apache.http.NameValuePair;
  10. import org.apache.http.client.config.RequestConfig;
  11. import org.apache.http.client.entity.UrlEncodedFormEntity;
  12. import org.apache.http.client.methods.CloseableHttpResponse;
  13. import org.apache.http.client.methods.HttpGet;
  14. import org.apache.http.client.methods.HttpPost;
  15. import org.apache.http.conn.ssl.DefaultHostnameVerifier;
  16. import org.apache.http.conn.util.PublicSuffixMatcher;
  17. import org.apache.http.conn.util.PublicSuffixMatcherLoader;
  18. import org.apache.http.entity.ContentType;
  19. import org.apache.http.entity.StringEntity;
  20. import org.apache.http.entity.mime.MultipartEntityBuilder;
  21. import org.apache.http.entity.mime.content.FileBody;
  22. import org.apache.http.entity.mime.content.StringBody;
  23. import org.apache.http.impl.client.CloseableHttpClient;
  24. import org.apache.http.impl.client.HttpClients;
  25. import org.apache.http.message.BasicNameValuePair;
  26. import org.apache.http.util.EntityUtils;
  27. public class HttpClientUtil {
  28. private RequestConfig requestConfig = RequestConfig.custom()
  29. .setSocketTimeout(15000)
  30. .setConnectTimeout(15000)
  31. .setConnectionRequestTimeout(15000)
  32. .build();
  33. private static HttpClientUtil instance = null;
  34. private HttpClientUtil(){}
  35. public static HttpClientUtil getInstance(){
  36. if (instance == null) {
  37. instance = new HttpClientUtil();
  38. }
  39. return instance;
  40. }
  41. /**
  42. * 发送 post请求
  43. * @param httpUrl 地址
  44. */
  45. public String sendHttpPost(String httpUrl) {
  46. HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
  47. return sendHttpPost(httpPost);
  48. }
  49. /**
  50. * 发送 post请求
  51. * @param httpUrl 地址
  52. * @param params 参数(格式:key1=value1&key2=value2)
  53. */
  54. public String sendHttpPost(String httpUrl, String params) {
  55. HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
  56. try {
  57. //设置参数
  58. StringEntity stringEntity = new StringEntity(params, "UTF-8");
  59. stringEntity.setContentType("application/x-www-form-urlencoded");
  60. httpPost.setEntity(stringEntity);
  61. } catch (Exception e) {
  62. e.printStackTrace();
  63. }
  64. return sendHttpPost(httpPost);
  65. }
  66. /**
  67. * 发送 post请求
  68. * @param httpUrl 地址
  69. * @param maps 参数
  70. */
  71. public String sendHttpPost(String httpUrl, Map<String, String> maps) {
  72. HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
  73. // 创建参数队列
  74. List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
  75. for (String key : maps.keySet()) {
  76. nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
  77. }
  78. try {
  79. httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
  80. } catch (Exception e) {
  81. e.printStackTrace();
  82. }
  83. return sendHttpPost(httpPost);
  84. }
  85. /**
  86. * 发送 post请求(带文件)
  87. * @param httpUrl 地址
  88. * @param maps 参数
  89. * @param fileLists 附件
  90. */
  91. public String sendHttpPost(String httpUrl, Map<String, String> maps, List<File> fileLists) {
  92. HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
  93. MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
  94. for (String key : maps.keySet()) {
  95. meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN));
  96. }
  97. for(File file : fileLists) {
  98. FileBody fileBody = new FileBody(file);
  99. meBuilder.addPart("files", fileBody);
  100. }
  101. HttpEntity reqEntity = meBuilder.build();
  102. httpPost.setEntity(reqEntity);
  103. return sendHttpPost(httpPost);
  104. }
  105. /**
  106. * 发送Post请求
  107. * @param httpPost
  108. * @return
  109. */
  110. private String sendHttpPost(HttpPost httpPost) {
  111. CloseableHttpClient httpClient = null;
  112. CloseableHttpResponse response = null;
  113. HttpEntity entity = null;
  114. String responseContent = null;
  115. try {
  116. // 创建默认的httpClient实例.
  117. httpClient = HttpClients.createDefault();
  118. httpPost.setConfig(requestConfig);
  119. // 执行请求
  120. response = httpClient.execute(httpPost);
  121. entity = response.getEntity();
  122. responseContent = EntityUtils.toString(entity, "UTF-8");
  123. } catch (Exception e) {
  124. e.printStackTrace();
  125. } finally {
  126. try {
  127. // 关闭连接,释放资源
  128. if (response != null) {
  129. response.close();
  130. }
  131. if (httpClient != null) {
  132. httpClient.close();
  133. }
  134. } catch (IOException e) {
  135. e.printStackTrace();
  136. }
  137. }
  138. return responseContent;
  139. }
  140. /**
  141. * 发送 get请求
  142. * @param httpUrl
  143. */
  144. public String sendHttpGet(String httpUrl) {
  145. HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
  146. return sendHttpGet(httpGet);
  147. }
  148. /**
  149. * 发送 get请求Https
  150. * @param httpUrl
  151. */
  152. public String sendHttpsGet(String httpUrl) {
  153. HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
  154. return sendHttpsGet(httpGet);
  155. }
  156. /**
  157. * 发送Get请求
  158. * @param httpPost
  159. * @return
  160. */
  161. private String sendHttpGet(HttpGet httpGet) {
  162. CloseableHttpClient httpClient = null;
  163. CloseableHttpResponse response = null;
  164. HttpEntity entity = null;
  165. String responseContent = null;
  166. try {
  167. // 创建默认的httpClient实例.
  168. httpClient = HttpClients.createDefault();
  169. httpGet.setConfig(requestConfig);
  170. // 执行请求
  171. response = httpClient.execute(httpGet);
  172. entity = response.getEntity();
  173. responseContent = EntityUtils.toString(entity, "UTF-8");
  174. } catch (Exception e) {
  175. e.printStackTrace();
  176. } finally {
  177. try {
  178. // 关闭连接,释放资源
  179. if (response != null) {
  180. response.close();
  181. }
  182. if (httpClient != null) {
  183. httpClient.close();
  184. }
  185. } catch (IOException e) {
  186. e.printStackTrace();
  187. }
  188. }
  189. return responseContent;
  190. }
  191. /**
  192. * 发送Get请求Https
  193. * @param httpPost
  194. * @return
  195. */
  196. private String sendHttpsGet(HttpGet httpGet) {
  197. CloseableHttpClient httpClient = null;
  198. CloseableHttpResponse response = null;
  199. HttpEntity entity = null;
  200. String responseContent = null;
  201. try {
  202. // 创建默认的httpClient实例.
  203. PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString()));
  204. DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
  205. httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
  206. httpGet.setConfig(requestConfig);
  207. // 执行请求
  208. response = httpClient.execute(httpGet);
  209. entity = response.getEntity();
  210. responseContent = EntityUtils.toString(entity, "UTF-8");
  211. } catch (Exception e) {
  212. e.printStackTrace();
  213. } finally {
  214. try {
  215. // 关闭连接,释放资源
  216. if (response != null) {
  217. response.close();
  218. }
  219. if (httpClient != null) {
  220. httpClient.close();
  221. }
  222. } catch (IOException e) {
  223. e.printStackTrace();
  224. }
  225. }
  226. return responseContent;
  227. }
  228. }

三、测试代码

  1. package cn.tzz.apache.httpclient;
  2. import java.io.File;
  3. import java.util.ArrayList;
  4. import java.util.HashMap;
  5. import java.util.List;
  6. import java.util.Map;
  7. import org.junit.Test;
  8. public class HttpClientUtilTest {
  9. @Test
  10. public void testSendHttpPost1() {
  11. String responseContent = HttpClientUtil.getInstance()
  12. .sendHttpPost("http://localhost:8089/test/send?username=test01&password=123456");
  13. System.out.println("reponse content:" + responseContent);
  14. }
  15. @Test
  16. public void testSendHttpPost2() {
  17. String responseContent = HttpClientUtil.getInstance()
  18. .sendHttpPost("http://localhost:8089/test/send", "username=test01&password=123456");
  19. System.out.println("reponse content:" + responseContent);
  20. }
  21. @Test
  22. public void testSendHttpPost3() {
  23. Map<String, String> maps = new HashMap<String, String>();
  24. maps.put("username", "test01");
  25. maps.put("password", "123456");
  26. String responseContent = HttpClientUtil.getInstance()
  27. .sendHttpPost("http://localhost:8089/test/send", maps);
  28. System.out.println("reponse content:" + responseContent);
  29. }
  30. @Test
  31. public void testSendHttpPost4() {
  32. Map<String, String> maps = new HashMap<String, String>();
  33. maps.put("username", "test01");
  34. maps.put("password", "123456");
  35. List<File> fileLists = new ArrayList<File>();
  36. fileLists.add(new File("D://test//httpclient//1.png"));
  37. fileLists.add(new File("D://test//httpclient//1.txt"));
  38. String responseContent = HttpClientUtil.getInstance()
  39. .sendHttpPost("http://localhost:8089/test/sendpost/file", maps, fileLists);
  40. System.out.println("reponse content:" + responseContent);
  41. }
  42. @Test
  43. public void testSendHttpGet() {
  44. String responseContent = HttpClientUtil.getInstance()
  45. .sendHttpGet("http://localhost:8089/test/send?username=test01&password=123456");
  46. System.out.println("reponse content:" + responseContent);
  47. }
  48. @Test
  49. public void testSendHttpsGet() {
  50. String responseContent = HttpClientUtil.getInstance()
  51. .sendHttpsGet("https://www.baidu.com");
  52. System.out.println("reponse content:" + responseContent);
  53. }
  54. }
  55. @RequestMapping(value = "/test/send")
  56. @ResponseBody
  57. public Map<String, String> sendPost(HttpServletRequest request) {
  58. Map<String, String> maps = new HashMap<String, String>();
  59. String username = request.getParameter("username");
  60. String password = request.getParameter("password");
  61. maps.put("username", username);
  62. maps.put("password", password);
  63. return maps;
  64. }
  65. @RequestMapping(value = "/test/sendpost/file",method=RequestMethod.POST)
  66. @ResponseBody
  67. public Map<String, String> sendPostFile(@RequestParam("files") MultipartFile [] files,HttpServletRequest request) {
  68. Map<String, String> maps = new HashMap<String, String>();
  69. String username = request.getParameter("username");
  70. String password = request.getParameter("password");
  71. maps.put("username", username);
  72. maps.put("password", password);
  73. try {
  74. for(MultipartFile file : files){
  75. String fileName = file.getOriginalFilename();
  76. fileName = new String(fileName.getBytes(),"UTF-8");
  77. InputStream is = file.getInputStream();
  78. if (fileName != null && !("".equals(fileName))) {
  79. File directory = new File("D://test//httpclient//file");
  80. if (!directory.exists()) {
  81. directory.mkdirs();
  82. }
  83. String filePath = ("D://test//httpclient//file") + File.separator + fileName;
  84. FileOutputStream fos = new FileOutputStream(filePath);
  85. byte[] buffer = new byte[1024];
  86. while (is.read(buffer) > 0) {
  87. fos.write(buffer, 0, buffer.length);
  88. }
  89. fos.flush();
  90. fos.close();
  91. maps.put("file--"+fileName, "uploadSuccess");
  92. }
  93. }
  94. } catch (Exception e) {
  95. e.printStackTrace();
  96. }
  97. return maps;
  98. }

原文链接:http://tzz6.iteye.com/blog/2224757

发表评论

表情:
评论列表 (有 0 条评论,856人围观)

还没有评论,来说两句吧...

相关阅读