转载地址:https://www.breakyizhan.com/java/3608.htm
准备
我们首先需要知道至少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格式并通过&连接。
使用(可选)查询参数激发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(); // ...
无论哪种方式,如果另一边是a HttpServlet,那么它的doGet()方法将被调用并且参数将被提供HttpServletRequest#getParameter()。
出于测试目的,您可以将响应主体打印到stdout中,如下所示:
try (Scanner scanner = new Scanner(response)) { String responseBody = scanner.useDelimiter("\A").next(); System.out.println(responseBody); }
使用查询参数激发HTTP POST请求
设置URLConnection#setDoOutput()为true隐式设置请求方法为POST。标准HTTP POST作为Web表单的类型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任意<input type="hidden">元素的对放入查询字符串中。
您也可以将获得的投射URLConnection到HttpURLConnection并使用它HttpURLConnection#setRequestMethod()。但是,如果你想使用的输出连接,您仍需要设置URLConnection#setDoOutput()到true。
HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection(); httpConnection.setRequestMethod("POST"); // ...
无论哪种方式,如果另一边是a HttpServlet,那么它的doPost()方法将被调用并且HttpServletRequest#getParameter()将获得对应的参数。
实际上触发HTTP请求
您可以明确地触发HTTP请求URLConnection#connect(),但是当您想要获取有关HTTP响应的任何信息时(例如响应正文使用等),请求将自动按需触发URLConnection#getInputStream()。上面的例子确实如此,所以这个connect()调用实际上是多余的。
收集HTTP响应信息
- HTTP响应状态:
你需要在HttpURLConnection这里。如有必要,先将它投射。
int status = httpConnection.getResponseCode();
- HTTP响应标头:
for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { System.out.println(header.getKey() + "=" + header.getValue()); }
- HTTP响应编码:
当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. }
维护会话session
服务器端会话session通常由一个cookie支持。一些网络表单要求您登录和/或由会话进行跟踪。您可以使用CookieHandlerAPI来维护Cookie。在所有HTTP请求之前,你需要准备一个CookieManager具有CookiePolicy中ACCEPT_ALL发送。
// 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标头。您基本上需要Set-Cookie从登录或第一个GET请求的响应中获取所有头,然后通过后续请求传递它。
// Gather all cookies on the first request. URLConnection connection = new URL(url).openConnection(); List<String> cookies = 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);。这可能会导致OutOfMemoryException您同时发送大量的POST请求(例如上传文件)。为了避免这种情况,你想设置HttpURLConnection#setFixedLengthStreamingMode()。
httpConnection.setFixedLengthStreamingMode(contentLength);
但是如果事先不知道内容长度,那么可以通过相应地设置来使用分块流模式HttpURLConnection#setChunkedStreamingMode()。这将设置将强制请求主体以块形式发送的HTTP Transfer-Encoding标头chunked。以下示例将以1KB的块形式发送主体。
httpConnection.setChunkedStreamingMode(1024);
用户代理
可能会发生请求返回意外的响应,但它可以在真正的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.
使用最近浏览器中的用户代理字符串。
错误处理
如果HTTP响应代码是4nn(客户端错误)或5nn(服务器错误),那么您可能需要阅读HttpURLConnection#getErrorStream()以查看服务器是否发送了任何有用的错误信息。
InputStream error = ((HttpURLConnection) connection).getErrorStream();
如果HTTP响应代码是-1,则连接和响应处理出错。这个HttpURLConnection实现在旧的JRE中存在一些问题,使得连接保持活跃状态。您可能需要将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(); }
如果另一边是a HttpServlet,那么它的doPost()方法将被调用,并且这些部分将可以通过HttpServletRequest#getPart()(注意,因此不是 getParameter()等等!)。这个getPart()方法是比较新的,它在Servlet 3.0中引入(Glassfish 3,Tomcat 7等)。在Servlet 3.0之前,最好的选择是使用Apache Commons FileUpload来解析multipart/form-data请求。
处理不可信或错误配置的HTTPS站点
有时您需要连接HTTPS网址,也许是因为您正在编写网络抓取工具。在这种情况下,您可能会遇到javax.net.ssl.SSLException: Not trusted server certificate一些HTTPS站点,这些站点没有及时更新其SSL证书,java.security.cert.CertificateException: No subject alternative DNS name matching [hostname] found或者javax.net.ssl.SSLProtocolException: handshake alert: unrecognized_name,这两个错误是HTTPS的某些配置错误的站点上。
以下一次运行的static初始值设定项在您的网页抓取工具类中应该HttpsURLConnection对这些HTTPS网站更为宽松,从而不会再抛出这些异常。
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); } }