Java Spring Boot RestTemplate调用Latam接口无响应无报错求助
开启HTTP请求全量日志
在Spring配置文件中添加日志配置,打印RestTemplate的所有请求细节,对比和Postman的请求是否完全一致:logging.level.org.springframework.web.client.RestTemplate=DEBUG logging.level.org.springframework.http=DEBUG或者自定义
ClientHttpRequestInterceptor手动记录请求头、参数和响应:template.getInterceptors().add((request, body, execution) -> { System.out.println("Request URI: " + request.getURI()); System.out.println("Request Headers: " + request.getHeaders()); ClientHttpResponse response = execution.execute(request, body); System.out.println("Response Status: " + response.getStatusCode()); return response; });设置请求超时时间
RestTemplate默认未设置超时,可能导致请求一直阻塞。手动配置超时参数:SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setConnectTimeout(5000); // 连接超时5秒 factory.setReadTimeout(10000); // 读取超时10秒 RestTemplate template = new RestTemplate(factory);检查参数编码问题
代码中outFrom参数传入了已编码的%3A,UriComponentsBuilder会自动对特殊字符编码,导致重复编码成%253A,服务器无法识别。改为传入原始未编码字符串:.queryParam("outFrom","2022-11-15T15:00:00.000Z")或者禁用自动编码:
UriComponents uri = UriComponentsBuilder.newInstance() // ...其他参数 .queryParam("outFrom","2022-11-15T15%3A00%3A00.000Z") .encode(false) .build();校验请求头的合理性
GET请求不需要设置Content-Type头,服务器可能对此有校验,建议移除该配置;另外将User-Agent改为更贴近浏览器的真实值(比如Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36),避免被服务器拦截。捕获所有异常
包裹代码块,捕获所有可能的异常并打印栈信息,排查是否有隐藏异常:try { ResponseEntity<String> response = template.exchange(uri.toUriString(), HttpMethod.GET, httpEntity, String.class); System.out.println(response); } catch (Exception e) { e.printStackTrace(); }抓包对比请求差异
使用WireShark或tcpdump抓取Java程序和Postman发出的HTTP请求包,对比请求方法、请求头、参数、TLS版本等细节,定位差异点。检查代理配置
如果Postman使用了系统代理或公司代理,需要给RestTemplate配置相同的代理:SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy-host", 8080)); factory.setProxy(proxy); RestTemplate template = new RestTemplate(factory);
内容的提问来源于stack exchange,提问作者Guilherme Silva

