RestTemplate的学习与使用

RestTemplate的学习与使用

最近在开发过程中遇到使用接口传输数据,了解到到RestTemplate

1、 源码分析


public class RestTemplate extends InterceptingHttpAccessor implements RestOperations {
		public RestTemplate(ClientHttpRequestFactory requestFactory) {
        this();
        this.setRequestFactory(requestFactory);
    }
}

// SimpleClientHttpRequestFactory  实现了ClientHttpRequestFactory  可以设置请求时间和超时时间等...
public class SimpleClientHttpRequestFactory implements ClientHttpRequestFactory, AsyncClientHttpRequestFactory {
    // 设置参数
    private static final int DEFAULT_CHUNK_SIZE = 4096;
    @Nullable
    private Proxy proxy;
    private boolean bufferRequestBody = true;
    private int chunkSize = 4096;
    private int connectTimeout = -1;
    private int readTimeout = -1;
    private boolean outputStreaming = true;
    @Nullable
    private AsyncListenableTaskExecutor taskExecutor;
}

2、 创建Util

public class ConnectionUtil {
	public static RestTemplate getConnectionFactory(){
	    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
	    factory.setConnectTimeout(5000);
	    factory.setReadTimeout(5000);
	    RestTemplate restTemplate = new RestTemplate(factory);
	        // 设置请求返回的编码格式
        List<HttpMessageConverter<?>> httpMessageConverters = restTemplate.getMessageConverters();
        httpMessageConverters.stream().forEach(httpMessageConverter -> {
            if(httpMessageConverter instanceof StringHttpMessageConverter){
                StringHttpMessageConverter messageConverter = (StringHttpMessageConverter) httpMessageConverter;
                messageConverter.setDefaultCharset(Charset.forName("UTF-8"));
            }
        });
	    return restTemplate;
	}
}

3、post请求


// 设置请求参数  
Map<String, Object> param = new HashMap<>();
param.put("username", username);
param.put("password", password);

String url = loginOn_URL;

// post请求try-catch包起来
try {
    RestTemplate restTemplate = ConnectionUtil.getConnectionFactory();
    //设置contentType类型
    HttpHeaders headers = new HttpHeaders();
    // 设置请求内容类型
    headers.setContentType(MediaType.APPLICATION_JSON);
    // 保持长连接
    headers.add("Connection", "Keep-Alive");
    // 设置Authorization身份验证  
    headers.add("Authorization", "Bearer " + Token);
    HttpEntity<Map<String, Object>> request = new HttpEntity(param, headers);
    // 直接返回结果
    String result = restTemplate.postForObject(url, request, String.class);
    // 返回结果转换成JSONObject
    JSONObject resultJo = JSONObject.parseObject(result);
    // 得到返回结果参数
    String xxx = resultJo.getString("xxx")
} catch (Exception e) {
    log.error("post error");
    throw new RuntimeException("post error");
}

4、get请求


// 1 请求参数在body中,格式为json的设置 
Map<String, Object> param = new HashMap<>();
param.put("ProviderID", ProviderID);
String url = getStatus_URL;

JSONObject resultJo = new JSONObject();
try {
    RestTemplate restTemplate = ConnectionUtil.getConnectionFactory();
  
    HttpHeaders headers = new HttpHeaders();
    //设置contentType类型
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add("Authorization", "Bearer " + Token);
    headers.add("Connection", "Keep-Alive");
    HttpEntity<Map<String, Object>> request = new HttpEntity(param, headers);
 // 要使用这个方法  不使用getForObject
    ResponseEntity<String> resEntity = restTemplate.exchange(url, HttpMethod.GET, request, String.class);
    resultJo = JSON.parseObject(resEntity.getBody());
    log.info("get result=" + resultJo);
    
} catch (Exception e) {
    log.error("get error");
    throw new RuntimeException("get error");
}

// 2 请求参数直接拼接到url路径上的
Map<String, Object> param = new HashMap<>();
long timeMillis = System.currentTimeMillis();
param.put("ProviderID", ProviderID);
param.put("Date", timeMillis);

String url = getStaticMessage + param.get("ProviderID") + "&Date=" + param.get("Date");
JSONObject resultJo = new JSONObject();
    try {
       RestTemplate restTemplate = ConnectionUtil.getConnectionFactory();
            //设置contentType类型
            HttpHeaders headers = new HttpHeaders();
            headers.add("Authorization", "Bearer " + Token);
            HttpEntity<String> request = new HttpEntity(null, headers);
            ResponseEntity<String> resEntity = restTemplate.exchange(url, HttpMethod.GET, request, String.class);

            resultJo = JSONObject.parseObject(resEntity.getBody());
            System.out.println("the vehicleInfo result=" + resultJo);

    } catch (Exception e) {
        log.error("the vehicleInfo error");
        throw new RuntimeException("the vehicleInfo error");
    }
      

5、文件内容转换成base64 的转换


// 根据本地路径将图片设置成base64格式
private String changeBase64(String url) {
	// 本地文件路径
    url = "D:/record saved/alarmpic/9860223/2021-12-31/9860223_082001_00-01.jpg";
    InputStream in = null;
    byte[] data = null;
    // 读取图片字节数组
    try {
        in = new FileInputStream(url);
        data = new byte[in.available()];
        in.read(data);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 输出字节数组的长度
    log.info("the byte length=" + data.length);
    /**
    *将字节数组转换成为base64格式
    */
    /* 
    * 刚开始网上查到的这个方法,不推荐使用  会在末尾添加换行符,
    * 传参数的时候会有问题,报400 bad request  
	 BASE64Encoder encoder = new BASE64Encoder();
	 encoder.encode(data);
	*/
    //  这个方法是jdk自带的,可以不考虑换行符的问题,推荐使用
    String code = Base64.getEncoder().encodeToString(data);
    return code;
}

<think>好的,我现在需要帮用户解决关于JavaRestTemplate进行POST请求使用方法或示例的问题。首先,用户明确提到了RestTemplate的POST请求,所以我得回忆一下相关的知识,并结合提供的引用内容来组织回答。 首先,我需要确认用户的需求。用户可能是一个正在学习Java开发人员,可能对RestTemplate不太熟悉,需要具体的示例和使用方法。用户提供的引用中有三个例子,分别涉及不同的POST请求场景,比如表单提交、GET请求和嵌套JSON参数。我需要从中提取有用的信息,并结合最佳实践来回答。 接下来,我要考虑如何结构化回答。用户希望步骤清晰,所以可能需要分点说明不同的POST请求方式。例如,表单提交、JSON对象、嵌套JSON以及文件上传等。每个部分需要代码示例和解释,同时确保语法正确。 然后,查看引用内容。引用1展示了使用MultiValueMap传递表单参数,引用3处理了多层嵌套JSON参数的情况。引用2虽然主要是GET请求,但可能对RestTemplate的基本使用有帮助。我需要将这些例子整合到回答中,确保覆盖常见的POST用例。 需要注意的是,用户可能对RestTemplate的配置或异常处理不太清楚,比如设置请求头、处理响应等。所以在每个示例中,应该包括必要的细节,比如设置Content-Type,处理返回结果等。 另外,用户的问题可能涉及到不同版本的Spring或RestTemplate,但提供的引用中没有提到版本差异,所以暂时假设用户使用的是较新的版本,但可能需要指出常见的注意事项,比如RestTemplate的未来替代方案(如WebClient)。 最后,生成相关问题部分需要考虑用户可能的后续疑问,比如参数传递方式、异常处理、性能优化等。确保问题主题相关,帮助用户深入理解。 现在,我需要整理这些思路,形成结构化的回答,确保符合用户的要求:使用中文,正确格式,分步骤说明,引用示例,并生成相关问题。同时,注意引用标识的正确添加,比如在提到表单参数时引用[^1],处理嵌套JSON时引用[^3]。</think>### Java RestTemplate POST请求使用方法及示例 根据Spring框架的HTTP客户端使用场景,RestTemplate的POST请求主要有以下四种典型使用方式,具体实现步骤如下: #### 一、表单参数提交(x-www-form-urlencoded) 使用`MultiValueMap`封装表单数据,适合普通键值对传输: ```java RestTemplate template = new RestTemplate(); String url = "http://api.example.com/login"; // 1. 构建表单参数 MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add("username", "admin"); params.add("password", "secure123"); // 2. 发送请求(自动添加FormHttpMessageConverter) ResponseEntity<String> response = template.postForEntity(url, params, String.class); ``` 此方法默认使用`application/x-www-form-urlencoded`格式[^1] #### 二、JSON对象提交(application/json) 处理JSON请求体需手动指定消息转换器: ```java HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); // 1. 构建嵌套JSON对象 Map<String, Object> payload = new HashMap<>(); payload.put("orderId", 1001); payload.put("items", Arrays.asList("itemA", "itemB")); // 2. 创建请求实体 HttpEntity<Map<String, Object>> entity = new HttpEntity<>(payload, headers); // 3. 发送请求(需配置Jackson库) String result = template.postForObject(url, entity, String.class); ``` 需确保引入`jackson-databind`依赖以实现自动序列化[^3] #### 三、复杂嵌套JSON结构 处理多层嵌套结构建议使用DTO对象: ```java // 1. 定义嵌套结构类 @Data class QueryParams { private String region; private List<String> filters; } @Data class RequestBody { private String apiVersion; private QueryParams query; } // 2. 构建请求体 RequestBody body = new RequestBody(); body.setApiVersion("v2.0"); body.setQuery(new QueryParams("CN", Arrays.asList("filter1","filter2"))); // 3. 发送请求 ResponseEntity<ResponseDTO> response = template.postForEntity( url, new HttpEntity<>(body, headers), ResponseDTO.class ); ``` 推荐使用POJO对象替代Map结构增强可维护性 #### 四、文件上传(multipart/form-data) ```java MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>(); parts.add("file", new FileSystemResource("report.pdf")); parts.add("metadata", "{\"category\":\"finance\"}"); HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(parts, headers); template.postForLocation(url, entity); ``` 需配置`FormHttpMessageConverter`支持文件传输 ### 关键配置项 1. 消息转换器配置: ```java RestTemplate template = new RestTemplate(Arrays.asList( new StringHttpMessageConverter(), new MappingJackson2HttpMessageConverter() )); ``` 2. 超时设置(需`SimpleClientHttpRequestFactory`) 3. 异常处理:建议覆盖`DefaultResponseErrorHandler`
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值