前言:
因为目前负责公司第三方对接问题,涉及到形形色色的接口调用,最近遇到一个很奇怪的问题,调用对方接口时,对方要求一个参数必须字符串使用utf-8编码,然后我们这边开始调用,测试,发现没有问题,调用一切正常,然后把对应的文件发送到项目上测试,但是发现他们调用总是失败,联系了一下对方公司的技术人员,找了下原因,发现这个编码的字符串他们接收到的是乱码,然后开始了找问题之路。最后终于找到了一种解决方式的办法,记录一下,可能各位会有更好的办法。
解决问题的思路:
1.首先对方需要的参数经过utf-8编码过的,所以我们这边参数传递之前进行编码,如下图中的调用方式,当然此处可以使用别的jar包,比如URLConnection 、HttpClient等等:
public static String post(String url,String paraStr,int timeout) { String result = ""; CloseableHttpClient httpClient = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(url); try { post.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36"); post.setConfig(RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(6000).build()); post.setHeader("Content-type", "application/json;charset=utf-8"); post.setEntity(new StringEntity(paraStr,"utf-8")); CloseableHttpResponse response = httpClient.execute(post); if(response.getStatusLine().getStatusCode()==org.apache.http.HttpStatus.SC_OK){ result = EntityUtils.toString(response.getEntity()); LOG.info("#####################调用接口返回的结果为:{}",result); } }catch(Exception e) { LOG.info(e.getMessage(),e); }finally { post.releaseConnection(); try { httpClient.close(); } catch (IOException e) { LOG.info(e.getMessage(),e); } } return result; } public static String post(String url,Map<String,Object> paraMap) { String result = ""; CloseableHttpClient httpClient = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(url); try { post.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36"); post.setConfig(RequestConfig.custom().setSocketTimeout(6000).setConnectTimeout(6000).build()); //这里发送post请求 List<NameValuePair> param = new ArrayList<>(); //建立一个NameValuePair数组,用于存储欲传送的参数 for(String key :paraMap.keySet()) { param.add(new BasicNameValuePair(key, Convert.toStr(paraMap.get(key)))); } //添加参数 post.setEntity(new UrlEncodedFormEntity(param, "UTF-8")); CloseableHttpResponse response = httpClient.execute(post); if(response.getStatusLine().getStatusCode()==org.apache.http.HttpStatus.SC_OK){ result = EntityUtils.toString(response.getEntity()); LOG.info("#####################调用下载接口返回的结果为:{}",result); } }catch(Exception e) { LOG.info(e.getMessage(),e); }finally { post.releaseConnection(); try { httpClient.close(); } catch (IOException e) { LOG.info(e.getMessage(),e); } } return result; }
2.修改tomcat配置server.xml中的编码
3.发现问题还是没有解决,然后就觉得是项目上环境的问题了,修改tomcat的bin文件下的catalina.bat文件,添加编码
然后测试发现问题解决。
当然可能还会有别的解决办法,因为这个问题我这边遇到了好几次了,所以记录下解决的过程,以备下次参考