RestTemplate调用外部接口异常排查

最近有个同事反馈,开发的产品,调用外部接口时(页面类似postman,允许用户配置接口的参数,并调用),一直报错,postman调用是可以的。
本地排查后,发现确实调用失败,代码中使用的是restTemplate,使用okhttp和python,都正常。restTemplate中更换RequestFactory为OkHttp3ClientHttpRequestFactory也可以,使用抓包软件抓取本地两次调用(分别使用restTemplate和okhttp),比对tcp数据后发现,restTemplate缺少了客户配置的一个请求头 origin,debug后,发现restTemplate默认的RequestFactory是SimpleClientHttpRequestFactor,底层为java.net.HttpURLConnection
。而 HttpURLConnection里面 有一个校验请求头的方法isRestrictedHeader:,包含了 private static final String[] restrictedHeaders = new String[]{"Access-Control-Request-Headers", "Access-Control-Request-Method", "Connection", "Content-Length", "Content-Transfer-Encoding", "Host", "Keep-Alive", "Origin", "Trailer", "Transfer-Encoding", "Upgrade", "Via"};
里面的header,在最终组装connection的时候,匹配的就会被忽略。
可行的解决方案:1、使用OkHttp3ClientHttpRequestFactory 2、代码中增加 System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
3、使用okhttp替换restTemplate

posted @ 2025-03-13 11:21  Gwanda  阅读(119)  评论(0)    收藏  举报