Java使用HttpClient封装get、post请求

你的名字 2022-05-24 05:34 417阅读 0赞

Java使用HttpClient封装get、post请求


  1. import lombok.extern.slf4j.Slf4j;
  2. import org.apache.commons.lang3.StringUtils;
  3. import org.apache.http.HttpEntity;
  4. import org.apache.http.NameValuePair;
  5. import org.apache.http.client.entity.UrlEncodedFormEntity;
  6. import org.apache.http.client.methods.CloseableHttpResponse;
  7. import org.apache.http.client.methods.HttpGet;
  8. import org.apache.http.client.methods.HttpPost;
  9. import org.apache.http.client.methods.HttpUriRequest;
  10. import org.apache.http.client.utils.URLEncodedUtils;
  11. import org.apache.http.impl.client.CloseableHttpClient;
  12. import org.apache.http.impl.client.HttpClients;
  13. import org.apache.http.message.BasicNameValuePair;
  14. import org.apache.http.util.EntityUtils;
  15. import java.io.IOException;
  16. import java.io.UnsupportedEncodingException;
  17. import java.net.URI;
  18. import java.util.ArrayList;
  19. import java.util.List;
  20. /**
  21. * <pre>
  22. * Http Client工具
  23. * </pre>
  24. *
  25. * @author hailiang.xu
  26. * @version 1.0
  27. * @since 2018/5/16 14:06
  28. */
  29. @Slf4j
  30. public class HttpClient {
  31. private static CloseableHttpClient httpclient = HttpClients.custom().build();
  32. private String url;
  33. private List<NameValuePair> nameValuePairs;
  34. private HttpUriRequest httpMessage;
  35. private HttpStatusFeedback statusFeedback;
  36. private boolean hasPost;
  37. public static void main(String[] args) throws IOException {
  38. System.out.println(new HttpClient()
  39. // .get("http://open.api.tianyancha.com/services/v4/open/baseinfo?id=22822&name=北京百度网讯科技有限公司")
  40. .get("http://open.api.tianyancha.com/services/v4/open/baseinfo")
  41. .addParameter("name", "北京百度网讯科技有限公司")
  42. .addHeader("Authorization", "******")
  43. .execute());
  44. }
  45. public HttpClient get(String url) {
  46. return service(url, new HttpGet(url), false);
  47. }
  48. public HttpClient post(String url) {
  49. return service(url, new HttpPost(url), true);
  50. }
  51. private HttpClient service(String url, HttpUriRequest httpMessage, boolean hasPost) {
  52. validateUrl(url);
  53. initFlag(url, hasPost);
  54. this.httpMessage = httpMessage;
  55. return this;
  56. }
  57. private void validateUrl(String url) {
  58. log.info("验证URL[{}]是否为空", url);
  59. if (StringUtils.isBlank(url)) {
  60. throw new IllegalArgumentException();
  61. }
  62. }
  63. public String execute() throws IOException {
  64. setParameter();
  65. log.info("访问请求地址[{}]获取结果", this.url);
  66. CloseableHttpResponse response = httpclient.execute(httpMessage);
  67. HttpEntity entity = response.getEntity();
  68. String result = EntityUtils.toString(entity, "utf-8");
  69. return result;
  70. }
  71. private void setParameter() throws UnsupportedEncodingException {
  72. log.info("添加请求参数到请求主体上");
  73. if (httpMessage instanceof HttpGet) {
  74. if (nameValuePairs != null && !nameValuePairs.isEmpty()) {
  75. String tmp = URLEncodedUtils.format(nameValuePairs, "utf-8");
  76. this.url += (this.url.contains("?") ? "&" : "?") + tmp;
  77. }
  78. ((HttpGet) httpMessage).setURI(URI.create(this.url));
  79. } else if (httpMessage instanceof HttpPost) {
  80. ((HttpPost) httpMessage).setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));
  81. }
  82. }
  83. private void initFlag(String url, boolean hasPost) {
  84. this.url = url;
  85. this.hasPost = hasPost;
  86. }
  87. public HttpClient addHeader(String key, String value) {
  88. log.info("校验请求主体是否存在");
  89. if (this.httpMessage == null)
  90. throw new NullPointerException("未调用get或post方法");
  91. log.info("设置请求头");
  92. this.httpMessage.setHeader(key, value);
  93. return this;
  94. }
  95. public synchronized HttpClient addParameter(String key, String value) {
  96. if (this.nameValuePairs == null) {
  97. this.nameValuePairs = new ArrayList<>();
  98. }
  99. log.info("添加请求参数[{}, {}]到内存", key, value);
  100. this.nameValuePairs.add(new BasicNameValuePair(key, value));
  101. return this;
  102. }
  103. public HttpClient statusFeedback(HttpStatusFeedback statusFeedback) {
  104. this.statusFeedback = statusFeedback;
  105. return this;
  106. }
  107. public boolean isSuccess() {
  108. return statusFeedback.isSuccess();
  109. }
  110. public boolean noData() {
  111. return statusFeedback.noData();
  112. }
  113. public String getStatusCode() {
  114. return statusFeedback.getStatusCode();
  115. }
  116. }

发表评论

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

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

相关阅读