根据 url 执行请求,并返回结果。

前提依赖

后续完善:)

核心代码

  1. import com.alibaba.fastjson.JSON;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.google.common.collect.Maps;
  4. import net.super0.sellbox.meta.entity.constant.ResponseResult;
  5. import org.apache.commons.lang3.StringUtils;
  6. import org.apache.http.NameValuePair;
  7. import org.apache.http.client.entity.UrlEncodedFormEntity;
  8. import org.apache.http.client.methods.CloseableHttpResponse;
  9. import org.apache.http.client.methods.HttpGet;
  10. import org.apache.http.client.methods.HttpPost;
  11. import org.apache.http.client.utils.URIBuilder;
  12. import org.apache.http.entity.StringEntity;
  13. import org.apache.http.impl.client.CloseableHttpClient;
  14. import org.apache.http.message.BasicNameValuePair;
  15. import org.apache.http.util.EntityUtils;
  16. import org.slf4j.Logger;
  17. import org.slf4j.LoggerFactory;
  18. import org.springframework.beans.factory.annotation.Autowired;
  19. import org.springframework.cglib.beans.BeanMap;
  20. import org.springframework.stereotype.Service;
  21. import java.io.IOException;
  22. import java.net.URISyntaxException;
  23. import java.nio.charset.Charset;
  24. import java.util.ArrayList;
  25. import java.util.List;
  26. import java.util.Map;
  27. @Service
  28. public class HttpRemoteService {
  29. private static final Logger logger = LoggerFactory.getLogger(HttpRemoteService.class);
  30. private static final String DEFAULT_ENCODE = "UTF-8";
  31. private static final String DEFAULT_CONTENT_TYPE = "application/json";
  32. @Autowired
  33. private CloseableHttpClient httpClient;
  34. }

处理 Get 请求

  1. /**
  2. * GET请求处理器
  3. *
  4. * @param url 地址
  5. * @param header 请求头
  6. * @param param 请求参数
  7. * @param clazz 返回类型
  8. * @param <T>
  9. * @return
  10. */
  11. public <T> T executeGet(String url, Map<String, String> header, Map<String, Object> param, Class<T> clazz) {
  12. T responseResult = null;
  13. CloseableHttpResponse response = null;
  14. try {
  15. URIBuilder uriBuilder = new URIBuilder(url);
  16. if (param != null) {
  17. for (Map.Entry<String, Object> entry : param.entrySet()) {
  18. uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
  19. }
  20. }
  21. HttpGet httpGet = new HttpGet(uriBuilder.build());
  22. if (header != null && header.size() > 0) {
  23. header.forEach(httpGet::addHeader);
  24. }
  25. log.info("http get 请求url:{}, param:{}", httpGet.getURI(), param);
  26. response = httpClient.execute(httpGet);
  27. String result = EntityUtils.toString(response.getEntity(), Charset.forName(DEFAULT_ENCODE));
  28. // log.info("http get 返回原始值 result:{}", result);
  29. if (StringUtils.isNotEmpty(result)) {
  30. responseResult = JSON.parseObject(result, clazz);
  31. }
  32. } catch (Exception e) {
  33. log.error("executeGet error", e);
  34. } finally {
  35. if (response != null) {
  36. EntityUtils.consumeQuietly(response.getEntity());
  37. }
  38. }
  39. return responseResult;
  40. }

处理 Post 请求

  1. /**
  2. * POST请求处理器
  3. *
  4. * @param url 地址
  5. * @param header 请求头
  6. * @param paramMap 请求参数
  7. * @param jsonParam 请求体
  8. * @param clazz 返回的类型
  9. * @param <T>
  10. * @return
  11. */
  12. public <T> T executePost(String url, Map<String, String> header, Map<String, Object> paramMap, JSONObject jsonParam,
  13. Class<T> clazz) {
  14. CloseableHttpResponse response = null;
  15. T responseResult = null;
  16. try {
  17. URIBuilder uriBuilder = new URIBuilder(url);
  18. // 判断请求参数不为空
  19. if (paramMap != null) {
  20. for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
  21. uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
  22. }
  23. }
  24. // 声明httpPost请求
  25. HttpPost httpPost = new HttpPost(uriBuilder.build());
  26. // 判断请求头不为空
  27. if (header != null && header.size() > 0) {
  28. header.forEach(httpPost::addHeader);
  29. }
  30. // 判断请求体不为空
  31. if (jsonParam != null) {
  32. StringEntity entity = new StringEntity(jsonParam.toJSONString(), DEFAULT_ENCODE);
  33. entity.setContentEncoding(DEFAULT_ENCODE);
  34. entity.setContentType(DEFAULT_CONTENT_TYPE);
  35. httpPost.setEntity(entity);
  36. }
  37. // 使用HttpClient发起请求,返回response
  38. response = httpClient.execute(httpPost);
  39. if (response == null) {
  40. return null;
  41. }
  42. String result = EntityUtils.toString(response.getEntity(), Charset.forName(DEFAULT_ENCODE));
  43. if (StringUtils.isNotEmpty(result)) {
  44. responseResult = JSON.parseObject(result, clazz);
  45. }
  46. } catch (Exception e) {
  47. log.error("executePost error", e);
  48. } finally {
  49. if (response != null) {
  50. EntityUtils.consumeQuietly(response.getEntity());
  51. }
  52. }
  53. // 返回结果
  54. return responseResult;
  55. }

GET 获取字节流

  1. /**
  2. * http get 方法获取字节流
  3. *
  4. * @param url
  5. * @return
  6. */
  7. public byte[] executeGetForBytes(String url) {
  8. byte[] result = null;
  9. CloseableHttpResponse response = null;
  10. try {
  11. URIBuilder uriBuilder = new URIBuilder(url);
  12. HttpGet httpGet = new HttpGet(uriBuilder.build());
  13. response = httpClient.execute(httpGet);
  14. result = EntityUtils.toByteArray(response.getEntity());
  15. } catch (Exception e) {
  16. logger.error("executeGet error", e);
  17. } finally {
  18. if (response != null) {
  19. EntityUtils.consumeQuietly(response.getEntity());
  20. }
  21. }
  22. return result;
  23. }

将对象转换为字节流

  1. /**
  2. * 将对象装换为map
  3. *
  4. * @param bean
  5. * @return
  6. */
  7. private <T> Map<String, Object> beanToMap(T bean) {
  8. Map<String, Object> map = Maps.newHashMap();
  9. if (bean != null) {
  10. BeanMap beanMap = BeanMap.create(bean);
  11. for (Object key : beanMap.keySet()) {
  12. map.put(key + "", beanMap.get(key));
  13. }
  14. }
  15. return map;
  16. }