【JAVA springframework.http】如何发送HTTP请求

Springboot之restTemplate

java 复制代码
public Result doHandlePostJson(String restUri, String jsonData)
            throws Exception {

        Result result = null;

        try {

            // logger记录
            log.info("doHandlePostJson request restUri:" + restUri
                    + " sendData:" + jsonData);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity request = new HttpEntity(jsonData, headers);

            // 发送http服务请求
            ResponseEntity<String> response = restTemplate.postForEntity(
                    restUri, request, String.class);

            // 判断返回结果
            if (response.getStatusCode() == HttpStatus.OK) {

                // logger记录
                log.debug("doHandlePostJson restUri response success,interfaceUri:"
                        + restUri);

                // 获得返回结果
                String repData = response.getBody();

                // logger记录
                log.info("doHandlePostJson restUri response success,return data:"
                        + repData);

                // 返回成功
                result = Result.succeed(repData, "");

            } else {

                // logger记录
                log.info("doHandlePostJson restUri response error,interfaceUri:"
                        + restUri + " http status:" + response.getStatusCode());

                // 返回产品Gateway通讯异常错误
                result = Result.failed("请求外部系统异常");
            }

        } catch (ResourceAccessException e) {

            // logger记录
            log.error("doHandlePostJson restUri ResourceAccessException:", e);

            // 返回通讯异常错误
            result = Result.failed("请求外部系统超时");

        } catch (Exception e) {

            // logger记录
            log.error("doHandlePostJson restUri Exception:", e);

            // 返回通讯异常错误
            result = Result.failed("请求外部系统未知异常");
        } finally {

            // 关闭
        }

        return result;
    }

package org.springframework.http;

HttpHeaders

public class HttpHeaders implements MultiValueMap<String, String>, Serializable

HttpEntity

public class HttpEntity

HttpStatus

public enum HttpStatus

相关推荐
皮皮林5511 小时前
拒绝写重复代码,试试这套开源的 SpringBoot 组件,效率翻倍~
java·spring boot
顺风尿一寸5 小时前
从 Java NIO poll 到 Linux 内核 poll:一次系统调用的完整旅程
java
程途知微5 小时前
JVM运行时数据区各区域作用与溢出原理
java
华仔啊7 小时前
为啥不用 MP 的 saveOrUpdateBatch?MySQL 一条 SQL 批量增改才是最优解
java·后端
xiaoye20189 小时前
Lettuce连接模型、命令执行、Pipeline 浅析
java
beata12 小时前
Java基础-18:Java开发中的常用设计模式:深入解析与实战应用
java·后端
Seven9713 小时前
剑指offer-81、⼆叉搜索树的最近公共祖先
java
雨中飘荡的记忆1 天前
保证金系统入门到实战
java·后端
Nyarlathotep01131 天前
Java内存模型
java