Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用spring restTemplate 中文乱码(APIV3) #43

Closed
1440530275 opened this issue Feb 22, 2021 · 11 comments
Closed

使用spring restTemplate 中文乱码(APIV3) #43

1440530275 opened this issue Feb 22, 2021 · 11 comments

Comments

@1440530275
Copy link

//具体配置
CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(wxConfig.getMchId(), certSerialNo, privateKeys)
                .withValidator(new WechatPay2Validator(verifier))
                .build();
        HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
        this.restTemplate = new RestTemplate(clientHttpRequestFactory);

尝试过使用转换器进行转换, 但是是没有效果的。

可以通过更改spring的注入类方式进行实现, 但是觉得不是一个很好的实现方式。

  • org.springframework.http.client.HttpComponentsClientHttpRequest#executeInternal

微信这一侧默认的是UFT-8, 我认为最好的解决思路是, 更改WechatPay2Credentials.buildMessage, 将默认的方式ISO-8859-1转换为UTF-8, 避免中文乱码。

if (request.getOriginal() instanceof WechatPayUploadHttpPost) {
      body = ((WechatPayUploadHttpPost) request.getOriginal()).getMeta();
    } else if (request instanceof HttpEntityEnclosingRequest) {
      body = EntityUtils.toString(((HttpEntityEnclosingRequest) request).getEntity());
    }
@1440530275 1440530275 changed the title 使用spring restTemplate 中文乱码 使用spring restTemplate 中文乱码(APIV3) Feb 22, 2021
@xy-peng
Copy link
Contributor

xy-peng commented Feb 22, 2021

#42 中提到的使用有没有效果?

this.restTemplate.getMessageConverters()
        .add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));

我需要实验一下

@1440530275
Copy link
Author

1440530275 commented Feb 22, 2021

#42 中提到的使用有没有效果?

this.restTemplate.getMessageConverters()
        .add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));

我需要实验一下

使用过, 但是没有效果, 集成的方式和您的代码是一样的。我debug跟踪了流程, 主要原因不是在于转换器的问题。在spring
HttpComponentsClientHttpRequest#executeInternal 这个方法是直接new了一个httpClient的HttpEntity。我不知道是为什么没有将Content-Type的属性复制进去。所以在解析的时候使用了默认的ISO-8859-1进行解码

@xy-peng
Copy link
Contributor

xy-peng commented Feb 23, 2021

看了下stackoverflow上答案的代码,试试先移除原有的StringHttpMessageConverter

List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();
converters.removeIf(httpMessageConverter -> httpMessageConverter instanceof StringHttpMessageConverter);
converters.add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));

@1440530275
Copy link
Author

看了下stackoverflow上答案的代码,试试先移除原有的StringHttpMessageConverter

List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();
converters.removeIf(httpMessageConverter -> httpMessageConverter instanceof StringHttpMessageConverter);
converters.add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));

依然不行, 解析出来之后, 中文依旧乱码。我暂时先直接使用HttpClient来请求是没问题的, 集成RestTemplate就会乱码。

@xy-peng
Copy link
Contributor

xy-peng commented Feb 23, 2021

方便把整个工程打包发到我邮箱一下?注意去掉敏感信息,比如商户私钥

@1440530275
Copy link
Author

1440530275 commented Feb 24, 2021 via email

@xxoyt
Copy link

xxoyt commented Feb 24, 2021

可以试试在请求之前指定编码格式,
HttpHeaders headers = request.getHeaders(); ContentType contentType = ContentType.APPLICATION_JSON.withCharset(StandardCharsets.UTF_8); headers.add("Content-Type", contentType.toString());
因为默认EntityUtils.toString(final HttpEntity entity) 里的编码会从contentType里取。可以试试还未验证

@1440530275
Copy link
Author

1440530275 commented Feb 24, 2021 via email

@xy-peng
Copy link
Contributor

xy-peng commented Feb 26, 2021

是应答的数据出现乱码?

@1440530275
Copy link
Author

是应答的数据出现乱码?

不是, 就是单纯的请求过去就出现了乱码. "description":"?????(??)-Indosat???-5KIDR??"
因为最终还是通过WechatPay2Credentials.buildMessage来进行输出解码的呀!
导致了
WeChat9a9d8614126d1ee48d4a3874a823418c

因为新版APIV3 description是必填的 所以这个问题我必须要解决,但是在我的代码中我不想去覆写这个类来进行注入, 所以我暂时还是使用原生的HttpClient配合连接池使用。 但是坏处是无法做到整体资源进行整合托管, 例如异常处理等事情。所以希望作者能够提供一个好的解决方法。谢谢啦

@xy-peng xy-peng mentioned this issue Apr 7, 2021
xy-peng added a commit that referenced this issue Apr 9, 2021
* fix: #20, use getTarget() instead of getURI(), because the URI may be absolute URI (as above) or may be a relative URI.

* fix: #42,#43 buildMessage()使用toString(entity, utf-8)从entity中获得请求报文

* update version to 0.2.2
@xy-peng
Copy link
Contributor

xy-peng commented Apr 9, 2021

0.2.2,使用以下的测试代码ok。乱码应该是设置StringHttpMessageConverter可以解决的。

    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
    List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();
    converters.removeIf(httpMessageConverter -> httpMessageConverter instanceof StringHttpMessageConverter);
    converters.add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectMapper objectMapper = new ObjectMapper();

    ObjectNode rootNode = objectMapper.createObjectNode();
    rootNode.put("mchid","1900009191")
            .put("appid", "wxdace645e0bc2c424")
            .put("description", "Image形象店-深圳腾大-QQ公仔")
            .put("notify_url", "https://www.weixin.qq.com/wxpay/pay.php")
            .put("out_trade_no", "1217752501201407033233368018");
    rootNode.putObject("amount")
            .put("total", 1);
    rootNode.putObject("payer")
            .put("openid", "oUpF8uMuAJO_M2pxb1Q9zNjWeS6o");

    objectMapper.writeValue(bos, rootNode);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    org.springframework.http.HttpEntity<String> request =
            new org.springframework.http.HttpEntity<>(bos.toString(), headers);

    ResponseEntity<String> response = restTemplate.postForEntity(
            "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi", request, String.class);
    assertEquals(200, response.getStatusCode());

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants