如何使用java.net.URLConnection 发出并处理HTTP请求。
如何使用java.net.URLConnection 发出并处理HTTP请求。
在这里,经常被问到如何使用java.net.URLConnection
,而Oracle教程解释得太简洁了。
那个教程基本上只展示了如何发送一个GET请求并读取响应。它没有解释如何使用该方法,比如执行POST请求,设置请求头,读取响应头,处理cookies,提交HTML表单,上传文件等。
所以,我该如何使用java.net.URLConnection
来执行和处理“高级”HTTP请求?
在使用HTTP时,与其使用基类URLConnection
,通常更有用的是参考 HttpURLConnection
(因为当你在一个HTTP URL上请求 URLConnection.openConnection()
时,你会收到 URLConnection
的返回,但是这是一个抽象类)。
然后,你可以通过 httpURLConnection.setRequestMethod("POST")
来设置请求方法为 POST,而不是依靠 URLConnection#setDoOutput(true)
隐式地设置请求方法。这样做可能更自然,并且还允许你指定其他请求方法,如 PUT、DELETE 等。
它还提供了有用的HTTP常量,因此你可以这样做:
int responseCode = httpURLConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) {
首先,在此声明:所发布的代码片段都是基本示例。您需要自行处理类似于NullPointerException
、ArrayIndexOutOfBoundsException
等关键字和IOException
和RuntimeException
等显而易见的异常。
如果您正在开发Android而不是Java,则请注意,自API级别28介绍以来,明文HTTP请求已默认禁用。您应该使用HttpsURLConnection
,但如果真有必要,应在应用程序清单中启用clear text。
准备工作
我们首先需要知道至少URL和字符集。参数是可选的,取决于功能要求。
String url = "http://example.com"; String charset = "UTF-8"; // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name() String param1 = "value1"; String param2 = "value2"; // ... String query = String.format("param1=%s¶m2=%s", URLEncoder.encode(param1, charset), URLEncoder.encode(param2, charset));
查询参数必须采用name=value
格式,并由&
连接。通常还会使用指定的字符集对查询参数进行URL编码,使用URLEncoder#encode()
方法进行编码。
String#format()
仅用于方便。如果我需要字符串连接运算符+
超过两次,我会更喜欢使用它。
发出(可选)带查询参数的HTTP GET请求
这是一项微不足道的任务。这是默认的请求方法。
URLConnection connection = new URL(url + "?" + query).openConnection(); connection.setRequestProperty("Accept-Charset", charset); InputStream response = connection.getInputStream(); // ...
任何查询字符串都应使用?
连接到URL中。 Accept-Charset
标头可以提示服务器参数编码是什么。 如果您不发送任何查询字符串,则可以省略Accept-Charset
标头。如果不需要设置任何标头,则甚至可以使用URL#openStream()
快捷方式方法。
InputStream response = new URL(url).openStream(); // ...
无论如何,如果对方是一个HttpServlet
,则其doGet()
方法将被调用,并且可以使用HttpServletRequest#getParameter()
获得参数。
为了测试目的,您可以将响应正文打印到标准输出中:
try (Scanner scanner = new Scanner(response)) { String responseBody = scanner.useDelimiter("\\A").next(); System.out.println(responseBody); }
使用查询参数触发HTTP POST请求
将URLConnection#setDoOutput()
设置为true
会隐式将请求方法设置为POST。 类似Web表单的标准HTTP POST的类型为application / x-www-form-urlencoded
,其中将查询字符串写入请求正文。
URLConnection connection = new URL(url).openConnection(); connection.setDoOutput(true); // Triggers POST. connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset); try (OutputStream output = connection.getOutputStream()) { output.write(query.getBytes(charset)); } InputStream response = connection.getInputStream(); // ...
注意:当你想要以编程方式提交HTML表单时,不要忘记将任何元素的“name=value”对和你想要以编程方式“按下”的元素的“name=value”对放入查询字符串中(因为通常在服务器端使用它们来区分是否按下了按钮,以及如果是的话哪一个按钮被按下)。
你还可以将获取的URLConnection转换为HttpURLConnection并使用其HttpURLConnection#setRequestMethod()方法。但是,如果你试图将连接用于输出,你仍然需要将URLConnection#setDoOutput()设置为true。
HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection(); httpConnection.setRequestMethod("POST"); // ...
无论哪种方式,如果另一侧是HttpServlet,则将调用其doPost()方法,并且参数将通过HttpServletRequest#getParameter()可用。
实际发送HTTP请求
你可以使用URLConnection#connect()
显式地发送HTTP请求,但是当你想要获取关于HTTP响应的任何信息,例如使用URLConnection#getInputStream()
获取响应正文内容时,请求将会自动地按需发送。上述示例就是如此,因此connect()
调用实际上是多余的。
获取HTTP响应信息
这里需要使用HttpURLConnection
。如有必要,需要进行强制类型转换。
int status = httpConnection.getResponseCode();
-
for (Entry
> header : connection.getHeaderFields().entrySet()) { System.out.println(header.getKey() + "=" + header.getValue()); }
当Content-Type
包含charset
参数时,响应正文内容很可能是基于文本的,并且我们希望使用服务器指定的字符编码处理响应正文内容。
String contentType = connection.getHeaderField("Content-Type"); String charset = null; for (String param : contentType.replace(" ", "").split(";")) { if (param.startsWith("charset=")) { charset = param.split("=", 2)[1]; break; } } if (charset != null) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(response, charset))) { for (String line; (line = reader.readLine()) != null;) { // ... System.out.println(line)? } } } else { // It's likely binary content, use InputStream/OutputStream. }
会话维护
服务器端会话通常由cookie支持。某些Web表单要求您登录并/或通过会话进行跟踪。您可以使用CookieHandler
API来维护cookie。在发送所有HTTP请求之前,您需要准备一个CookieManager
,并使用ACCEPT_ALL
的CookiePolicy
来设置它。
// First set the default cookie manager. CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL)); // All the following subsequent URLConnections will use the same cookie manager. URLConnection connection = new URL(url).openConnection(); // ... connection = new URL(url).openConnection(); // ... connection = new URL(url).openConnection(); // ...
请注意,已知在某些情况下无法正确运行此方法。如果它对您不起作用,那么最好手动收集和设置cookie头。您基本上需要从登录或第一个GET
请求的响应中抓取所有Set-Cookie
头,然后通过后续请求来传递它们。
// Gather all cookies on the first request. URLConnection connection = new URL(url).openConnection(); Listcookies = connection.getHeaderFields().get("Set-Cookie"); // ... // Then use the same cookies on all subsequent requests. connection = new URL(url).openConnection(); for (String cookie : cookies) { connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]); } // ...
split(";", 2)[0]
的作用是摆脱服务器端不相关的cookie属性,如expires
、path
等。或者,您也可以使用cookie.substring(0, cookie.indexOf(';'))
来替代split()
。
流式模式
HttpURLConnection
默认情况下会在实际发送请求之前缓冲整个请求体,而不管您是否使用connection.setRequestProperty("Content-Length", contentLength);
设置了固定的内容长度。当您同时发送大型POST请求(例如上传文件)时,这可能导致OutOfMemoryException
。为了避免这种情况,您需要设置HttpURLConnection#setFixedLengthStreamingMode()
。
httpConnection.setFixedLengthStreamingMode(contentLength);
但如果内容长度真的事先未知,那么您可以通过适当设置HttpURLConnection#setChunkedStreamingMode()
来使用分块流模式。 这将使HTTP Transfer-Encoding
头设置为chunked
,这将强制请求主体以块的形式发送。 下面的示例将以1KB块的形式发送主体。
httpConnection.setChunkedStreamingMode(1024);
User-Agent
可能会发生请求返回意外响应,而在真实的Web浏览器中正常工作。 服务器端可能会阻止基于User-Agent
请求头的请求。 URLConnection
默认将其设置为Java/1.6.0_19
,其中最后一部分显然是JRE版本。 您可以按以下方式覆盖此设置:
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); // Do as if you're using Chrome 41 on Windows 7.
使用最近浏览器的User-Agent字符串。
错误处理
如果HTTP响应代码为4nn
(客户端错误)或5nn
(服务器错误),则您可能需要读取HttpURLConnection#getErrorStream()
以查看服务器是否发送了任何有用的错误信息。
InputStream error = ((HttpURLConnection) connection).getErrorStream();
如果HTTP响应代码为-1,则连接和响应处理出现了问题。在旧的JRE中,HttpURLConnection
实现对于保持连接不太稳定。您可能希望通过将http.keepAlive
系统属性设置为false
来关闭它。您可以在应用程序的开始时以编程方式执行此操作:
System.setProperty("http.keepAlive", "false");
上传文件
通常会使用multipart/form-data
编码来处理混合POST内容(二进制和字符数据)。编码在RFC2388中有更详细的描述。
String param = "value"; File textFile = new File("/path/to/file.txt"); File binaryFile = new File("/path/to/file.bin"); String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value. String CRLF = "\r\n"; // Line separator required by multipart/form-data. URLConnection connection = new URL(url).openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); try ( OutputStream output = connection.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true); ) { // Send normal param. writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF); writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); writer.append(CRLF).append(param).append(CRLF).flush(); // Send text file. writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF); writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset! writer.append(CRLF).flush(); Files.copy(textFile.toPath(), output); output.flush(); // Important before continuing with writer! writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary. // Send binary file. writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF); writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF); writer.append("Content-Transfer-Encoding: binary").append(CRLF); writer.append(CRLF).flush(); Files.copy(binaryFile.toPath(), output); output.flush(); // Important before continuing with writer! writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary. // End of multipart/form-data. writer.append("--" + boundary + "--").append(CRLF).flush(); }
如果另一方是一个HttpServlet
,则将调用其doPost()
方法,并且通过HttpServletRequest#getPart()
可用各个部分(注意,不是getParameter()
等等!)。但是,getPart()
方法相对较新,它是在Servlet 3.0(Glassfish 3、Tomcat 7等)中引入的。在Servlet 3.0之前,您最好使用Apache Commons FileUpload来解析multipart/form-data
请求。此外,还可以参见此答案,其中包含使用FileUpload和Servelt 3.0方法的示例。
处理不可信或错误配置的HTTPS网站
如果你是在为Android而不是Java进行开发,则要小心:如果你在开发过程中没有正确的证书部署,下面的解决方法可能会帮你度过难关。但是你不应该在生产环境中使用它。现在(2021年4月),如果检测到不安全的主机名验证程序,谷歌不会允许你的应用在Play商店中分发,详情见https://support.google.com/faqs/answer/7188426。
有时你需要连接HTTPS URL,也许是因为你正在编写网页爬虫。在这种情况下,你可能会在一些不更新SSL证书的HTTPS网站上遇到javax.net.ssl.SSLException:不信任的服务器证书
,或在一些错误配置的HTTPS网站上遇到java.security.cert.CertificateException:找不到与[hostname]匹配的主题备用DNS名称
或javax.net.ssl.SSLProtocolException:握手警报:unrecognized_name
等异常。
在你的网页爬虫类中运行以下一次性static
初始化器可以使HttpsURLConnection
更加宽容,从而不再抛出那些异常。
static { TrustManager[] trustAllCertificates = new TrustManager[] { new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; // Not relevant. } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { // Do nothing. Just allow them all. } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { // Do nothing. Just allow them all. } } }; HostnameVerifier trustAllHostnames = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; // Just allow them all. } }; try { System.setProperty("jsse.enableSNIExtension", "false"); SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCertificates, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(trustAllHostnames); } catch (GeneralSecurityException e) { throw new ExceptionInInitializerError(e); } }
最后的话
Apache HttpComponents HttpClient在这方面更加方便 🙂
解析和提取HTML
如果你只想从HTML中解析和提取数据,那么最好使用像Jsoup这样的HTML解析器。