java - 如何使用java.net.URLConnection触发和处理HTTP请求?

标签 java http httprequest httpurlconnection urlconnection

在这里经常问到java.net.URLConnection的使用,而Oracle tutorial太简洁了。

该教程基本上仅显示如何触发GET请求并读取响应。它没有任何地方说明如何使用它来执行POST请求,设置请求标头,读取响应标头,处理cookie,提交HTML表单,上传文件等。

因此,如何使用java.net.URLConnection触发和处理“高级” HTTP请求?

最佳答案

首先先声明一下:发布的代码段都是基本示例。您需要处理琐碎的IOExceptionRuntimeException(如NullPointerExceptionArrayIndexOutOfBoundsException)并自行整理。



准备中

我们首先需要至少了解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&param2=%s", 
     URLEncoder.encode(param1, charset), 
     URLEncoder.encode(param2, charset));


查询参数必须为name=value格式,并由&串联。通常,您还可以使用URL-encode使用指定的字符集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()可以使用参数。

为了进行测试,您可以将响应正文打印到stdout,如下所示:

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元素的<input type="hidden">对放入查询字符串中,当然也将name=value元素的<input type="submit">对放入其中您希望通过编程方式“按下”该按钮(因为通常在服务器端使用该按钮来区分是否按下了按钮,如果按下了按钮则区分是哪个按钮)。

您还可以将获得的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响应信息


HTTP response status

您需要在此处HttpURLConnection。如有必要,请先进行投射。

int status = httpConnection.getResponseCode();

HTTP response headers

for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
    System.out.println(header.getKey() + "=" + header.getValue());
}

HTTP response encoding

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请求之前,您需要准备CookieManagerCookiePolicyACCEPT_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属性,例如expirespath等。或者,也可以使用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);




用户代理

a request returns an unexpected response, while it works fine with a real web browser可能会发生。服务器端可能基于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.


使用recent browser中的User-Agent字符串。



错误处理

如果HTTP响应代码是4nn(客户端错误)或5nn(服务器错误),则您可能需要阅读HttpURLConnection#getErrorStream()以查看服务器是否发送了任何有用的错误信息。

InputStream error = ((HttpURLConnection) connection).getErrorStream();


如果HTTP响应代码为-1,则连接和响应处理出错。 HttpURLConnection的实现是在较旧的JRE中实现连接保持活动状态存在一些漏洞。您可能需要通过将http.keepAlive系统属性设置为false将其关闭。您可以通过以下方式在应用程序的开头以编程方式执行此操作:

System.setProperty("http.keepAlive", "false");




上载档案

通常,对混合的POST内容(二进制和字符数据)使用multipart/form-data编码。编码在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方法的示例,另请参见this answer



处理不受信任或配置错误的HTTPS站点

有时您需要连接HTTPS URL,这可能是因为您正在编写Web爬虫。在这种情况下,您可能在某些HTTPS站点上未保持其SSL证书最新的javax.net.ssl.SSLException: Not trusted server certificate,或者在某些配置错误的HTTPS站点上面临java.security.cert.CertificateException: No subject alternative DNS name matching [hostname] foundjavax.net.ssl.SSLProtocolException: handshake alert: unrecognized_name

Web爬网程序类中的以下一次性运行的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);
    }
}




最后的话

Apache HttpComponents HttpClient在这方面更加方便:)


HttpClient Tutorial
HttpClient Examples




解析和提取HTML

如果您只想从HTML解析和提取数据,那么最好使用HTML解析器,例如Jsoup


What are the pros/cons of leading HTML parsers in Java
How to scan and extract a webpage in Java

关于java - 如何使用java.net.URLConnection触发和处理HTTP请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42739213/

相关文章:

java - 从 mongodb 内部文档中的数组获取值

http - 为什么 SNDBUF 太低会破坏 HTTP?

c# - 如何在 C# 下向网络服务器发送执行 js 功能的请求?

angular - 如何仅在第一个请求完成时触发新的 http 请求并忽略/取消其间的所有其他请求

node.js - 如何使用 Node.JS 请求 HTTP Digest 身份验证?

java - 为什么 @JoinTable 上的 JPA (Hibernate) 外键定义不起作用?

java - 在 Play Framework 启动之前添加一些初始代码

java - 使用反射调用方法

Android WebView 有时不会在初始页面加载时发送请求 header

powershell - 如何在 PowerShell 中发布到 URL?