• 使用RestTemplate 进行远程接口调用工具类


    程序开发中,经常碰到需要远程接口调用的业务场景,一般的get请求直接使用Hutool工具类就很方便,但是Hutool的post请求有时候出现调用失败的问题。

    博主调试微信公众号的相关接口使用hutool就一直报错,我还以为是自己的参数不符合微信要求呢,结果换成自己的工具类调用腾讯,立刻就通了。

    所以这里把自己封装的工具类展示出来,以供参考或借鉴。

    1. import com.alibaba.fastjson.JSON;
    2. import com.alibaba.fastjson.JSONObject;
    3. import org.apache.commons.lang3.StringUtils;
    4. import org.springframework.http.HttpEntity;
    5. import org.springframework.http.HttpHeaders;
    6. import org.springframework.http.MediaType;
    7. import org.springframework.http.ResponseEntity;
    8. import org.springframework.web.client.RestTemplate;
    9. /**
    10. * restTemplate 远程访问工具类
    11. *
    12. * @author gbx
    13. * @since 2021-02-26 14:36
    14. */
    15. public class RestClientUtils {
    16. /**
    17. * 使用restTemplate发送post请求
    18. *
    19. * @param restTemplate 请求工具
    20. * @param uri 请求路径
    21. * @param token 访问令牌
    22. * @param jsonObject 请求参数
    23. * @param message 请求功能详情说明
    24. * @return 响应结果
    25. */
    26. public static String sendPostString(RestTemplate restTemplate, String uri, String token, JSONObject jsonObject, String message) {
    27. String body;
    28. try {
    29. HttpEntity formEntity = getFormEntity(jsonObject, token);
    30. body = restTemplate.postForEntity(uri, formEntity, String.class).getBody();
    31. } catch (Exception e) {
    32. throw new RuntimeException("调用上游服务器失败:" + message, e);
    33. }
    34. return body;
    35. }
    36. /**
    37. * 获取POST请求的请求体对象
    38. *
    39. * @param jsonObject 封装请求参数信息的实体
    40. * @param token 接口访问令牌
    41. * @return 处理结果
    42. */
    43. public static HttpEntity getFormEntity(JSONObject jsonObject, String token) {
    44. HttpHeaders headers = new HttpHeaders();
    45. MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
    46. headers.setContentType(type);
    47. headers.add("Accept", MediaType.APPLICATION_JSON.toString());
    48. if (StringUtils.isNotBlank(token)) {
    49. headers.add("token", token);
    50. }
    51. HttpEntity formEntity;
    52. if (jsonObject != null) {
    53. formEntity = new HttpEntity<>(jsonObject.toString(), headers);
    54. } else {
    55. formEntity = new HttpEntity<>(headers);
    56. }
    57. return formEntity;
    58. }
    59. }

    PS: 工具类中生成调用对象的时候,如果存在token,以约定的实际token key名为准,比如博主这里key就叫 token,所以直接加在header里,你如果叫 Authorization ,那你就在header中添加这个key。

  • 相关阅读:
    python:正则表达式符号
    学习c语音的自我感受
    Linux磁盘分区和管理
    数据结构:交换排序
    WEB基础
    rsync远程同步
    【c++】解决使用 std::map 时报错 no match for ‘operator<’
    使用Spring WebSocket实现实时通信功能
    Uniapp 应用消息通知插件 Ba-Notify
    Mysql分页、SSM项目分页实战
  • 原文地址:https://blog.csdn.net/yssa1125001/article/details/126285335