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);
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM