如题,原生代码,使用HttpURLConnection请求时候,获取302 Follow Redirect重定向时候,获取需要重定向的地址。
注意需要加上这句 connection.setInstanceFollowRedirects(false);
否则会抛出java.net.SocketException: Unexpected end of file from server,而获取不到重定向地址。
String url = "http://www.example.com"; String postContent = "data=somedata"; HttpURLConnection connection = null; connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); //这句关键,否则connection.getResponseCode()这句会抛出异常: java.net.SocketException: Unexpected end of file from server connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(60000 * 5); connection.setReadTimeout(60000 * 5); connection.getOutputStream().write(postContent.getBytes(StandardCharsets.UTF_8)); int responseCode = connection.getResponseCode(); if (responseCode == 302) { //重定向地址 String redirctLocation = connection.getHeaderField("Location"); }
文章评论