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

Springboot之restTemplate

  • https://blog.csdn.net/weixin_43702146/article/details/116567707
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, Serializable

HttpEntity

public class HttpEntity

HttpStatus

public enum HttpStatus

你可能感兴趣的:(HTTP,java,http)