Java测试中HttpURLConnection无法正确捕获HTTP 302问题排查
问题分析与解决办法
你遇到的矛盾点根源在于HttpURLConnection的自动重定向机制:
当你设置connection.setInstanceFollowRedirects(true);时,连接会自动跟随302重定向请求去访问目标地址(/test),此时getResponseCode()返回的是目标地址的响应码(也就是200),而不是初始请求(/rdrct)的302状态码。
根据你的测试目标,有两种修正方案:
方案1:验证初始请求返回302
如果你要测试的是/rdrct确实返回302重定向,只需要关闭自动跟随重定向:
@Test public void testRedirect() throws Exception { String uri = "http://localhost:" + port + "/rdrct"; URL url = new URL(uri); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 关闭自动跟随,获取初始请求的响应码 connection.setInstanceFollowRedirects(false); connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif," + "image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"); connection.connect(); int responseCode = connection.getResponseCode(); assertEquals(responseCode, 302); }
方案2:验证重定向最终成功返回200
如果你要测试的是重定向流程能正常到达/test并返回200,就保留自动跟随重定向,修改断言:
@Test public void testRedirect() throws Exception { String uri = "http://localhost:" + port + "/rdrct"; URL url = new URL(uri); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif," + "image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"); connection.connect(); int responseCode = connection.getResponseCode(); assertEquals(responseCode, 200); // 可选:验证重定向的目标地址是否正确 assertEquals(connection.getURL().getPath(), "/test"); }
内容的提问来源于stack exchange,提问作者p0tta
相关产品推荐
相关产品推荐

