HttpClient GET和POST请求 工具类

悠悠 2022-05-26 10:39 306阅读 0赞
  1. package cn.rojao.utils;
  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.HttpClients;
  23. import org.apache.http.message.BasicNameValuePair;
  24. import org.apache.http.util.EntityUtils;
  25. import org.apache.log4j.Logger;
  26. /**
  27. * @author ljh
  28. * @date 2018年04月28日
  29. * HttpClient工具类
  30. */
  31. public class HttpClientUtil {
  32. private static Logger logger = Logger.getLogger(HttpClientUtil.class);
  33. /**
  34. * get请求
  35. * @return
  36. */
  37. public static String doGet(String url) {
  38. try {
  39. //HttpClient client = new DefaultHttpClient();
  40. HttpClient client = HttpClients.createDefault();
  41. //发送get请求
  42. HttpGet request = new HttpGet(url);
  43. HttpResponse response = client.execute(request);
  44. /**请求发送成功,并得到响应**/
  45. if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  46. /**读取服务器返回过来的json字符串数据**/
  47. String strResult = EntityUtils.toString(response.getEntity());
  48. return strResult;
  49. }
  50. }
  51. catch (IOException e) {
  52. e.printStackTrace();
  53. }
  54. return null;
  55. }
  56. /**
  57. * post请求(用于key-value格式的参数)
  58. * @param url
  59. * @param params
  60. * @return
  61. */
  62. public static String doPost(String url, Map params){
  63. BufferedReader in = null;
  64. try {
  65. // 定义HttpClient
  66. //HttpClient client = new DefaultHttpClient();
  67. HttpClient client = HttpClients.createDefault();
  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,"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. public static void main(String[] args){
  149. try {
  150. System.out.println(doPost("http://10.10.1.77:9091/kk","{'kk':123,'ggg':232}"));
  151. System.out.println(doGet("http://10.10.1.77:9091/kk"));
  152. } catch (Exception e) {
  153. // TODO: handle exception
  154. e.printStackTrace();
  155. }
  156. }
  157. }

maven需要引入的包:


org.apache.httpcomponents
httpcore
4.4.5

org.apache.httpcomponents
httpclient
4.3.3

发表评论

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

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

相关阅读