httpclient接口返回结果中文显示问号

现象:

解决办法:StringEntity,要加个UTF-8参数

package com.sf.autotest.common;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

import javax.sound.midi.Soundbank;
import java.io.InputStream;
import java.io.IOException;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Set;


public class SendData {
    private static Logger log = LoggerFactory.getLogger(SendData.class);
    public static HashMap changeData;

    public static String sendXml(String resourcePath) throws IOException {
        HashMap<String, String> changeData = new HashMap<>();
        changeData.put("{{eno}}", "住院号");
        changeData.put("{{pid}}", "患者号");
        Set<String> keySet = changeData.keySet();

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(sfContant.auditcenter_url + "/api/v1/auditcenter");
        String xml = "";
        try (InputStream input = new ClassPathResource(resourcePath).getInputStream()) {
            xml = IOUtils.toString(input, StandardCharsets.UTF_8);
        }
        for (String key : keySet) {
            xml = xml.replace(key, changeData.get(key));
        }
        log.info("请求{}的入参为:\n{}", sfContant.auditcenter_url, xml);
        StringEntity requestEntity = new StringEntity(xml,"UTF-8");
        requestEntity.setContentType("text/plain");
        requestEntity.setContentEncoding("UTF-8");
        httpPost.setEntity(requestEntity);
        CloseableHttpResponse respose = httpClient.execute(httpPost);
        HttpEntity entity = respose.getEntity();
        String resBody  = EntityUtils.toString(entity);
//        System.out.println(resBody);

//        log.info("\n{}",EntityUtils.toString(entity,"utf-8"));
        return resBody;
    }



    public static void main(String[] args) throws IOException {
        String s = SendData.sendXml("audit.xml");
        System.out.println(s);



    }
}

特别注意:

EntityUtils.toString(entity),只能获取一次,再次访问会报错 流关闭

 

posted @ 2020-06-28 14:46  爱打盹的猫猫  阅读(2381)  评论(0编辑  收藏  举报