ERP系统汇率更新Java程序报HTTP 400错误排查求助
解决从央行官网获取汇率时的HTTP 400错误
核心问题分析
HTTP 400错误是服务器判定请求格式无效导致的,你的代码存在三个关键问题:
- 用POST请求访问静态页面,但浏览器正常访问该页面用的是GET请求,央行服务器可能拒绝POST请求该资源
- 代码注释掉了
User-Agent请求头,很多服务器会拦截无UA标识的请求,判定为非法爬虫 - 调用时传了
null作为POST参数,导致请求体格式异常,进一步触发400错误
方案1:改用GET请求(最直接有效,推荐)
目标页面是公开静态汇率页面,完全不需要POST请求,直接改用GET即可解决问题,替换代码如下:
public static String sendGet(String url) { BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); URLConnection conn = realUrl.openConnection(); // 设置必要请求头,必须包含User-Agent conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("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"); // 建立连接并读取响应 conn.connect(); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result; }
对应的调用代码修改为:
public static void main(String[] args) throws IOException{ String s1 = ChnExchRate.sendGet("http://www.pbc.gov.cn/zhengcehuobisi/125207/125217/125925/index.html"); }
方案2:保留POST请求(不推荐,无必要)
如果一定要沿用原有POST逻辑,需要修复两个关键问题:
- 恢复
User-Agent请求头设置 - 将
null参数替换为空字符串,避免请求体异常
修改后的sendPost方法:
public static String sendPost(String url, String param) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); URLConnection conn = realUrl.openConnection(); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); // 恢复User-Agent设置 conn.setRequestProperty("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"); conn.setDoOutput(true); conn.setDoInput(true); out = new PrintWriter(conn.getOutputStream()); // 用空字符串替代null,避免请求体格式错误 out.print(param == null ? "" : param); out.flush(); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result; }
对应的调用代码修改为:
public static void main(String[] args) throws IOException{ String s1 = ChnExchRate.sendPost("http://www.pbc.gov.cn/zhengcehuobisi/125207/125217/125925/index.html", ""); }
内容的提问来源于stack exchange,提问作者ClevyJSJ
相关产品推荐
相关产品推荐

