Java使用httpclient封装post请求和get请求

谁借莪1个温暖的怀抱¢ 2022-03-14 10:44 578阅读 0赞
  1. package com.marco.common;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.net.URI;
  6. import java.util.ArrayList;
  7. import java.util.Iterator;
  8. import java.util.List;
  9. import java.util.Map;
  10. import org.apache.http.HttpEntity;
  11. import org.apache.http.HttpResponse;
  12. import org.apache.http.HttpStatus;
  13. import org.apache.http.NameValuePair;
  14. import org.apache.http.StatusLine;
  15. import org.apache.http.client.HttpClient;
  16. import org.apache.http.client.entity.UrlEncodedFormEntity;
  17. import org.apache.http.client.methods.CloseableHttpResponse;
  18. import org.apache.http.client.methods.HttpGet;
  19. import org.apache.http.client.methods.HttpPost;
  20. import org.apache.http.entity.StringEntity;
  21. import org.apache.http.impl.client.CloseableHttpClient;
  22. import org.apache.http.impl.client.DefaultHttpClient;
  23. import org.apache.http.impl.client.HttpClients;
  24. import org.apache.http.message.BasicNameValuePair;
  25. import org.apache.http.protocol.HTTP;
  26. import org.apache.http.util.EntityUtils;
  27. import org.apache.log4j.Logger;
  28. /**
  29. * @author 马弦
  30. * @date 2017年10月23日 下午2:49
  31. * HttpClient工具类
  32. */
  33. public class HttpUtil {
  34. private static Logger logger = Logger.getLogger(HttpUtil.class);
  35. /**
  36. * get请求
  37. * @return
  38. */
  39. public static String doGet(String url) {
  40. try {
  41. HttpClient client = new DefaultHttpClient();
  42. //发送get请求
  43. HttpGet request = new HttpGet(url);
  44. HttpResponse response = client.execute(request);
  45. /**请求发送成功,并得到响应**/
  46. if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  47. /**读取服务器返回过来的json字符串数据**/
  48. String strResult = EntityUtils.toString(response.getEntity());
  49. return strResult;
  50. }
  51. }
  52. catch (IOException e) {
  53. e.printStackTrace();
  54. }
  55. return null;
  56. }
  57. /**
  58. * post请求(用于key-value格式的参数)
  59. * @param url
  60. * @param params
  61. * @return
  62. */
  63. public static String doPost(String url, Map params){
  64. BufferedReader in = null;
  65. try {
  66. // 定义HttpClient
  67. HttpClient client = new DefaultHttpClient();
  68. // 实例化HTTP方法
  69. HttpPost request = new HttpPost();
  70. request.setURI(new URI(url));
  71. //设置参数
  72. List<NameValuePair> nvps = new ArrayList<NameValuePair>();
  73. for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
  74. String name = (String) iter.next();
  75. String value = String.valueOf(params.get(name));
  76. nvps.add(new BasicNameValuePair(name, value));
  77. //System.out.println(name +"-"+value);
  78. }
  79. request.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8));
  80. HttpResponse response = client.execute(request);
  81. int code = response.getStatusLine().getStatusCode();
  82. if(code == 200){ //请求成功
  83. in = new BufferedReader(new InputStreamReader(response.getEntity()
  84. .getContent(),"utf-8"));
  85. StringBuffer sb = new StringBuffer("");
  86. String line = "";
  87. String NL = System.getProperty("line.separator");
  88. while ((line = in.readLine()) != null) {
  89. sb.append(line + NL);
  90. }
  91. in.close();
  92. return sb.toString();
  93. }
  94. else{ //
  95. System.out.println("状态码:" + code);
  96. return null;
  97. }
  98. }
  99. catch(Exception e){
  100. e.printStackTrace();
  101. return null;
  102. }
  103. }
  104. /**
  105. * post请求(用于请求json格式的参数)
  106. * @param url
  107. * @param params
  108. * @return
  109. */
  110. public static String doPost(String url, String params) throws Exception {
  111. CloseableHttpClient httpclient = HttpClients.createDefault();
  112. HttpPost httpPost = new HttpPost(url);// 创建httpPost
  113. httpPost.setHeader("Accept", "application/json");
  114. httpPost.setHeader("Content-Type", "application/json");
  115. String charSet = "UTF-8";
  116. StringEntity entity = new StringEntity(params, charSet);
  117. httpPost.setEntity(entity);
  118. CloseableHttpResponse response = null;
  119. try {
  120. response = httpclient.execute(httpPost);
  121. StatusLine status = response.getStatusLine();
  122. int state = status.getStatusCode();
  123. if (state == HttpStatus.SC_OK) {
  124. HttpEntity responseEntity = response.getEntity();
  125. String jsonString = EntityUtils.toString(responseEntity);
  126. return jsonString;
  127. }
  128. else{
  129. logger.error("请求返回:"+state+"("+url+")");
  130. }
  131. }
  132. finally {
  133. if (response != null) {
  134. try {
  135. response.close();
  136. } catch (IOException e) {
  137. e.printStackTrace();
  138. }
  139. }
  140. try {
  141. httpclient.close();
  142. } catch (IOException e) {
  143. e.printStackTrace();
  144. }
  145. }
  146. return null;
  147. }
  148. }

上述方法已过时, 下边为新的封装类

  1. /**
  2. * <p>Title: HttpUtil.java</p>
  3. * @author xiatian
  4. * @date 2019年3月4日
  5. */
  6. package com.weixin.util;
  7. import java.io.IOException;
  8. import java.net.URLEncoder;
  9. import java.util.Iterator;
  10. import java.util.Map;
  11. import org.apache.http.HttpEntity;
  12. import org.apache.http.HttpStatus;
  13. import org.apache.http.client.config.RequestConfig;
  14. import org.apache.http.client.methods.CloseableHttpResponse;
  15. import org.apache.http.client.methods.HttpGet;
  16. import org.apache.http.client.methods.HttpPost;
  17. import org.apache.http.entity.StringEntity;
  18. import org.apache.http.impl.client.CloseableHttpClient;
  19. import org.apache.http.impl.client.HttpClients;
  20. import org.apache.http.util.EntityUtils;
  21. import org.slf4j.Logger;
  22. import org.slf4j.LoggerFactory;
  23. /**
  24. * @author xl
  25. *
  26. */
  27. public class HttpUtil {
  28. private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
  29. private static final CloseableHttpClient httpClient;
  30. static {
  31. httpClient = HttpClients.createDefault();
  32. }
  33. /**
  34. * get请求
  35. *
  36. * @return
  37. */
  38. public static String doGet(String url) {
  39. CloseableHttpResponse response = null;
  40. try {
  41. // 发送get请求
  42. HttpGet httpGet = new HttpGet(url);
  43. // 配置请求参数
  44. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)
  45. .setConnectionRequestTimeout(1000).setSocketTimeout(6000).build();
  46. httpGet.setConfig(requestConfig);
  47. // 执行请求
  48. response = httpClient.execute(httpGet);
  49. // 建立的http连接,仍旧被response保持着,允许我们从网络socket中获取返回的数据
  50. // 为了释放资源,我们必须手动消耗掉response或者取消连接(使用CloseableHttpResponse类的close方法)
  51. /** 请求发送成功,并得到响应 **/
  52. if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  53. /** 读取服务器返回过来的json字符串数据 **/
  54. HttpEntity entity = response.getEntity();
  55. if (entity != null) {
  56. String strResult = EntityUtils.toString(entity, "UTF-8");
  57. /** 消耗掉entity对象 **/
  58. EntityUtils.consume(entity);
  59. return strResult;
  60. }
  61. }
  62. } catch (Exception e) {
  63. e.printStackTrace();
  64. } finally {
  65. if (response != null) {
  66. try {
  67. response.close();
  68. } catch (IOException e) {
  69. e.printStackTrace();
  70. }
  71. }
  72. }
  73. return null;
  74. }
  75. /**
  76. * post请求(请求参数是 name1=value1&name2=value2 的形式)
  77. *
  78. * @param url
  79. * @param params
  80. * @return
  81. */
  82. public static String doPost(String url, String params) {
  83. // 创建httpPost
  84. HttpPost httpPost = new HttpPost(url);
  85. httpPost.setHeader("Accept", "*/*");
  86. httpPost.setHeader("Accept-Charset", "UTF-8");
  87. httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
  88. StringEntity entity = new StringEntity(params, "UTF-8");
  89. httpPost.setEntity(entity);
  90. // 配置请求参数
  91. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)
  92. .setConnectionRequestTimeout(1000).setSocketTimeout(6000).build();
  93. httpPost.setConfig(requestConfig);
  94. // 执行请求
  95. CloseableHttpResponse response = null;
  96. try {
  97. response = httpClient.execute(httpPost);
  98. if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  99. HttpEntity responseEntity = response.getEntity();
  100. if (responseEntity != null) {
  101. String jsonString = EntityUtils.toString(responseEntity, "UTF-8");
  102. /** 消耗掉entity对象 **/
  103. EntityUtils.consume(responseEntity);
  104. return jsonString;
  105. }
  106. }
  107. } catch (Exception e) {
  108. e.printStackTrace();
  109. } finally {
  110. if (response != null) {
  111. try {
  112. response.close();
  113. } catch (IOException e) {
  114. e.printStackTrace();
  115. }
  116. }
  117. }
  118. return null;
  119. }
  120. /**
  121. * post请求(用于请求json格式的参数)
  122. *
  123. * @param url
  124. * @param params
  125. * @return
  126. */
  127. public static String doJsonPost(String url, String params) throws Exception {
  128. // 创建httpPost
  129. HttpPost httpPost = new HttpPost(url);
  130. httpPost.setHeader("Accept", "application/json");
  131. httpPost.setHeader("Content-Type", "application/json");
  132. StringEntity entity = new StringEntity(params, "UTF-8");
  133. httpPost.setEntity(entity);
  134. // 配置请求参数
  135. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)
  136. .setConnectionRequestTimeout(1000).setSocketTimeout(6000).build();
  137. httpPost.setConfig(requestConfig);
  138. // 执行请求
  139. CloseableHttpResponse response = null;
  140. try {
  141. response = httpClient.execute(httpPost);
  142. if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  143. HttpEntity responseEntity = response.getEntity();
  144. if (responseEntity != null) {
  145. String jsonString = EntityUtils.toString(responseEntity, "UTF-8");
  146. /** 消耗掉entity对象 **/
  147. EntityUtils.consume(responseEntity);
  148. return jsonString;
  149. }
  150. }
  151. } catch (Exception e) {
  152. e.printStackTrace();
  153. } finally {
  154. if (response != null) {
  155. try {
  156. response.close();
  157. } catch (IOException e) {
  158. e.printStackTrace();
  159. }
  160. }
  161. }
  162. return null;
  163. }
  164. /**
  165. * 将map对象转换为URL参数格式
  166. *
  167. * @param params
  168. * @return
  169. */
  170. public static String buildParam(Map<String, Object> params) {
  171. if (params.isEmpty()) {
  172. return "";
  173. }
  174. StringBuilder param = new StringBuilder();
  175. Iterator<String> keyItor = params.keySet().iterator();
  176. try {
  177. while (keyItor.hasNext()) {
  178. String key = keyItor.next();
  179. Object o = params.get(key);
  180. if (o == null) {
  181. param.append(key + "=&");
  182. } else {
  183. param.append(key + "=" + URLEncoder.encode(String.valueOf(o), "UTF-8") + "&");
  184. }
  185. }
  186. if (param.length() != 0) {
  187. param.deleteCharAt(param.length() - 1);
  188. }
  189. } catch (Exception ex) {
  190. logger.error(ex.getMessage());
  191. }
  192. return param.toString();
  193. }
  194. }

完!!!

发表评论

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

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

相关阅读