原创

获取数据出现乱码的解决办法


查看响应数据的编码格式是否正确
  • 若不正确可在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);
		}
	}
SpringBoot
  • 作者:陌攻(联系作者)
  • 发表时间:2020-05-30 18:53
  • 版权声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证)
  • 公众号转载:请在文末添加作者公众号二维码
  • 评论