RestTemplate调用三方接口获取数据时出现乱码的常见解决办法

查看响应数据的编码格式是否正确
  • 若不正确可在RestTemplate注入spring容器时进行修改,如下
package com.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.Charset;

@Configuration
public class RestTemplateConfig {

	@Autowired
	private RestTemplateBuilder builder;
	
	@Bean
	public RestTemplate restTemplate() {
		RestTemplate restTemplate = builder.build();
		restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(Charset.forName("ISO-8859-1")));
		return restTemplate;
	}
	
}

  • 或者直接修改返回的数据编码格式
dataStr=new String(dataStr.getBytes("UTF-8"),"ISO-8859-1");
查看接口返回的内容编码是否为gzip

在这里插入图片描述

  • 若为gzip则进行解码,如下

	/**
	 *
	 * @param url 第三方接口
	 * @return
	 */
	private Weather doGetData(String url) {
		//头部信息定义end
		try {
			ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

			if(response.getStatusCode() == HttpStatus.OK) {
				//开始gzip解码
				InputStream inWithCode = new ByteArrayInputStream(response.getBody().getBytes("ISO-8859-1"));
				GZIPInputStream gunzip = new GZIPInputStream(inWithCode);
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				byte[] buffer = new byte[256];
				int n;
				while ((n = gunzip.read(buffer))>= 0) {
					out.write(buffer, 0, n);
				}
				//gzip解码结束
				String dataStr = out.toString();
				//将数据封装到WeatherResponse对象中
				WeatherResponse wr = new ObjectMapper().readValue(dataStr, WeatherResponse.class);
				if(wr.getStatus().equals("1000")) {
					//返回响应数据
					return wr.getData();
				}else {
					throw new BusinessException("call weather api error");
				}
			}else {
				throw new BusinessException("call weather api error");
			}
		}catch(BusinessException e) {
			throw e;
		}catch(Exception e) {
			throw new BusinessException("call weather api error", e);
		}
	}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值