首页 > Java > 如何使用来触发和处理“高级”HTTP请求呢?java.net.URLConnection

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

上一篇 下一篇

这里经常被问到如何使用,而 Oracle 教程对此过于简洁。java.net.URLConnection

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

那么,如何使用来触发和处理“高级”HTTP请求呢?java.net.URLConnection

分割线

网友回答:

在使用HTTP时,引用基类几乎总是比基类更有用(因为当你在HTTP URL上请求时,它是一个抽象类,无论如何你都会得到)。HttpURLConnectionURLConnectionURLConnectionURLConnection.openConnection()

然后,您可以不依赖于将请求方法隐式设置为 POST,而是执行某些人可能会发现更自然的操作(并且还允许您指定其他请求方法,例如 PUTDELETE等)。URLConnection#setDoOutput(true)httpURLConnection.setRequestMethod("POST")

它还提供了有用的 HTTP 常量,因此您可以执行以下操作:

int responseCode = httpURLConnection.getResponseCode();

if (responseCode == HttpURLConnection.HTTP_OK) {

分割线

网友回答:

首先事先免责声明:发布的代码片段都是基本示例。您需要处理琐碎的IOExceptionRuntimeException,例如NullPointerExceptionArrayIndexOutOfBoundsException并自己组合。

如果您正在为 Android 而不是 Java 进行开发,请注意,自引入 API 级别 28 以来,默认情况下会禁用明文 HTTP 请求。建议使用 HttpsURLConnection,但如果确实有必要,可以在应用程序清单中启用明文。


准备

我们首先需要至少知道 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));

查询参数的格式必须由 连接。通常,您还将使用 对具有指定字符集的查询参数进行 URL 编码。name=value&URLEncoder#encode()

String#format() 只是为了方便起见。当我需要字符串连接运算符 + 两次以上时,我更喜欢它。


使用(可选)查询参数触发 HTTP GET 请求

这是一项微不足道的任务。这是默认的请求方法。

URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
// ...

任何查询字符串都应使用 连接到 URL。标头可能会提示服务器参数的编码方式。如果不发送任何查询字符串,则可以保留标头。如果您不需要设置任何标头,那么您甚至可以使用快捷方式方法。?Accept-CharsetAccept-CharsetURL#openStream()

InputStream response = new URL(url).openStream();
// ...

无论哪种方式,如果另一端是 ,则将调用其方法,并且参数将由 提供。HttpServletdoGet()HttpServletRequest#getParameter()

出于测试目的,您可以将响应正文打印为标准输出,如下所示:

try (Scanner scanner = new Scanner(response)) {
    String responseBody = scanner.useDelimiter("\A").next();
    System.out.println(responseBody);
}

使用查询参数触发 HTTP POST 请求

将 设置为 隐式将请求方法设置为 POST。与 Web 表单一样的标准 HTTP POST 的类型是将查询字符串写入请求正文的类型。URLConnection#setDoOutput()trueapplication/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">

还可以将获取的转换为并改用其。但是,如果您尝试使用连接进行输出,则仍需要设置为 .URLConnectionHttpURLConnectionHttpURLConnection#setRequestMethod()URLConnection#setDoOutput()true

HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection();
httpConnection.setRequestMethod("POST");
// ...

无论哪种方式,如果另一端是 ,则将调用其方法,并且参数将由 提供。HttpServletdoPost()HttpServletRequest#getParameter()


实际触发 HTTP 请求

您可以使用 显式触发 HTTP 请求,但当您想要获取有关 HTTP 响应的任何信息(例如响应正文使用等)时,将按需自动触发该请求。上面的例子正是这样做的,所以调用实际上是多余的。URLConnection#connect()URLConnection#getInputStream()connect()


收集 HTTP 响应信息

  1. HTTP 响应状态:

你需要一个这里。如有必要,请先投射它。HttpURLConnection

    int status = httpConnection.getResponseCode();
  1. HTTP 响应标头:
     for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
         System.out.println(header.getKey() + "=" + header.getValue());
     }
    
  2. HTTP 响应编码:

当 包含参数时,响应正文可能是基于文本的,我们希望使用服务器端指定的字符编码处理响应正文。Content-Typecharset

    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 表单要求您登录和/或由会话跟踪。您可以使用 API 来维护 Cookie。在发送所有 HTTP 请求之前,您需要准备一个带有 of 的。CookieHandlerCookieManagerCookiePolicyACCEPT_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-CookieGET

// 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]);
}
// ...

这是为了摆脱与服务器端无关的cookie属性,如,等。或者,您也可以使用 代替 。split(";", 2)[0]expirespathcookie.substring(0, cookie.indexOf(';'))split()


流媒体模式

默认情况下,在实际发送请求正文之前,无论您是否使用 .这可能会导致 s,只要您同时发送大型 POST 请求(例如上传文件)。为避免这种情况,您需要设置 .HttpURLConnectionconnection.setRequestProperty("Content-Length", contentLength);OutOfMemoryExceptionHttpURLConnection#setFixedLengthStreamingMode()

httpConnection.setFixedLengthStreamingMode(contentLength);

但是,如果事先确实不知道内容长度,那么您可以通过设置相应的内容来利用分块流模式。这将设置 HTTP 标头,该标头将强制以块的形式发送请求正文。以下示例将以 1 KB 的块发送正文。HttpURLConnection#setChunkedStreamingMode()Transfer-Encodingchunked

httpConnection.setChunkedStreamingMode(1024);

用户代理

请求可能会返回意外响应,而它与真正的 Web 浏览器一起工作。服务器端可能正在根据请求标头阻止请求。默认情况下,会将其设置为最后一部分显然是 JRE 版本的位置。您可以按如下方式覆盖此设置:User-AgentURLConnectionJava/1.6.0_19

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 响应代码是(客户端错误)或(服务器错误),则可能需要阅读 以查看服务器是否发送了任何有用的错误信息。4nn5nnHttpURLConnection#getErrorStream()

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

如果 HTTP 响应代码为 -1,则连接和响应处理出现问题。该实现在较旧的 JRE 中,在保持连接活动方面有些错误。您可能希望通过将系统属性设置为 来关闭它。您可以在应用程序开始时以编程方式执行此操作,方法是:HttpURLConnectionhttp.keepAlivefalse

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

上传文件

您通常会对混合 POST 内容(二进制和字符数据)使用编码。RFC2388 中更详细地描述了编码。multipart/form-data

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 = "rn"; // 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();
}

如果另一端是 ,则其方法将被调用,并且部件将可用(注意,因此不是等等!然而,该方法相对较新,它在Servlet 3.0(Glassfish 3,Tomcat 7等)中引入。在 Servlet 3.0 之前,最好的选择是使用 Apache Commons FileUpload 来解析请求。另请参阅此答案以获取FileUpload和Servelt 3.0方法的示例。HttpServletdoPost()HttpServletRequest#getPart()getParameter()getPart()multipart/form-data


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

如果您正在为 Android 而不是 Java 进行开发,请小心:如果您在开发过程中没有部署正确的证书,下面的解决方法可能会节省您的时间。但是您不应该将其用于生产。这些天(2021 年 7188426 月),如果 Google 检测到不安全的主机名验证工具,Google 将不允许在 Play 商店中分发您的应用,请参阅 https://support.google.com/faqs/answer/<>。

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

Web 抓取工具类中的以下一次性运行初始值设定项应该对这些 HTTPS 站点更加宽松,从而不再抛出这些异常。staticHttpsURLConnection

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 教程
  • HttpClient 示例

解析和提取 HTML

如果你想要的只是从HTML中解析和提取数据,那么最好使用像Jsoup这样的HTML解析器。

  • Java 中领先的 HTML 解析器的优缺点是什么
  • 如何在 Java 中扫描和提取网页

分割线

网友回答:

受到这个问题和Stack Overflow上其他问题的启发,我创建了一个最小的开源basic-http-client,它体现了这里找到的大多数技术。

google-http-java-client也是一个很好的开源资源。

模板简介:该模板名称为【如何使用来触发和处理“高级”HTTP请求呢?java.net.URLConnection】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【Java】栏目查找您需要的精美模板。

相关搜索
  • 下载密码 lanrenmb
  • 下载次数 183次
  • 使用软件 Sublime/Dreamweaver/HBuilder
  • 文件格式 编程语言
  • 文件大小 暂无信息
  • 上传时间 02-16
  • 作者 网友投稿
  • 肖像权 人物画像及字体仅供参考
栏目分类 更多 >
热门推荐 更多 >
微信公众平台 响应式 单页式简历模板 自适应 微信素材 html5 微信图片 微信文章 企业网站 微信模板
您可能会喜欢的其他模板