小言_互联网的博客

JAVA工具类 [ 调用HTTP 请求 ]

498人阅读  评论(0)

 

 

 


  
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. package org.apache.dolphinscheduler.common.utils;
  18. import org.apache.commons.io.Charsets;
  19. import org.apache.dolphinscheduler.common.Constants;
  20. import org.apache.http.HttpEntity;
  21. import org.apache.http.client.config.RequestConfig;
  22. import org.apache.http.client.methods.CloseableHttpResponse;
  23. import org.apache.http.client.methods.HttpUriRequest;
  24. import org.apache.http.client.methods.RequestBuilder;
  25. import org.apache.http.entity.StringEntity;
  26. import org.apache.http.impl.client.CloseableHttpClient;
  27. import org.apache.http.impl.client.HttpClientBuilder;
  28. import org.apache.http.impl.client.HttpClients;
  29. import org.apache.http.util.EntityUtils;
  30. import org.slf4j.Logger;
  31. import org.slf4j.LoggerFactory;
  32. import java.io.IOException;
  33. import java.nio.charset.StandardCharsets;
  34. import java.util.Map;
  35. import com.alibaba.fastjson.JSONObject;
  36. /**
  37. * http utils
  38. */
  39. public class HttpUtils {
  40. /**
  41. * application json
  42. */
  43. protected static final String APPLICATION_JSON = "application/json";
  44. public static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);
  45. /**
  46. * get http request content
  47. * @param url url
  48. * @return http get request response content
  49. */
  50. public static String get( String url){
  51. String responseContent = null;
  52. try {
  53. responseContent = request( "GET",url, null, null, null);
  54. } catch (IOException e) {
  55. e.printStackTrace();
  56. }
  57. return responseContent;
  58. }
  59. /**
  60. *
  61. * @param method : GET PUT HEAD PUT DELETE
  62. * @param url
  63. * @param headerParams
  64. * @param parameterParams
  65. * @param bodyParams
  66. * @return
  67. * @throws IOException
  68. */
  69. public static String request( String method ,
  70. String url ,
  71. Map< String, String > headerParams,
  72. Map< String, String > parameterParams ,
  73. Map< String, String > bodyParams) throws IOException {
  74. String responseContent = null;
  75. CloseableHttpResponse response = null;
  76. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(Constants.HTTP_CONNECT_TIMEOUT)
  77. .setConnectionRequestTimeout(Constants.HTTP_CONNECTION_REQUEST_TIMEOUT)
  78. .setSocketTimeout(Constants.SOCKET_TIMEOUT)
  79. .setRedirectsEnabled( true)
  80. .build();
  81. HttpClientBuilder httpClientBuilder = HttpClients.custom().
  82. setDefaultRequestConfig(requestConfig);
  83. CloseableHttpClient client = httpClientBuilder.build();
  84. RequestBuilder builder = RequestBuilder.create(method) ;
  85. JSONObject jsonParam = new JSONObject();
  86. if( null != parameterParams && parameterParams.size() > 0){
  87. for ( String key : parameterParams.keySet()) {
  88. builder.addParameter(key, parameterParams.get(key));
  89. }
  90. }
  91. if( null != bodyParams && bodyParams.size() > 0){
  92. for ( String key : bodyParams.keySet()) {
  93. jsonParam.put(key, bodyParams.get(key));
  94. }
  95. }
  96. StringEntity postingString = new StringEntity(jsonParam.toString(), Charsets.UTF_8);
  97. postingString.setContentEncoding(StandardCharsets.UTF_8.name());
  98. postingString.setContentType(APPLICATION_JSON);
  99. builder.setEntity(postingString);
  100. HttpUriRequest request = builder.setUri(url).build();
  101. if( null != headerParams && headerParams.size() > 0){
  102. for ( String key : headerParams.keySet()) {
  103. request.addHeader(key, headerParams.get(key));
  104. }
  105. }
  106. try {
  107. response = client.execute(request);
  108. HttpEntity entity = response.getEntity();
  109. if (entity != null) {
  110. responseContent = EntityUtils.toString(entity, Constants.UTF_8);
  111. } else{
  112. logger.warn( "http entity is null");
  113. }
  114. } catch (Exception e){
  115. logger.error(e.getMessage(),e);
  116. } finally {
  117. try {
  118. if (response != null) {
  119. EntityUtils.consume(response.getEntity());
  120. response.close();
  121. }
  122. } catch (IOException e) {
  123. logger.error(e.getMessage(),e);
  124. }
  125. if (!request.isAborted()) {
  126. request.abort();
  127. }
  128. try {
  129. client.close();
  130. } catch (IOException e) {
  131. logger.error(e.getMessage(),e);
  132. }
  133. }
  134. return responseContent;
  135. }
  136. }

 


转载:https://blog.csdn.net/zhanglong_4444/article/details/105785581
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场