问题

在这里经常会问到java.net.URLConnection的用法,以及关于它的Oracle tutorial

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

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


#1 热门回答(2514 赞)

首先是免责声明:发布的代码片段都是基本示例。你需要处理普通的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格式,并由连接。您通常也会使用URLEncoder #codes()使用指定的字符集查询参数。
String#format()只是为了方便。当我需要String连接运算符``时,我更喜欢它两次以上。

###使用(可选)查询参数激发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。标准的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表单,不要忘记将任何<input type =“hidden”>元素的name = value对放入查询字符串中,当然还要将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响应状态:您需要在此处使用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];
        打破;
    }
}

如果(charset!= null){
    尝试(BufferedReader阅读器=新的BufferedReader(新的InputStreamReader(响应,字符集))){
        for(String line;(line = reader.readLine())!= null;){
            // ... System.out.println(line)?
        }
    }
} else {
    //这可能是二进制内容,使用InputStream / OutputStream。
}

###维护会话

服务器端会话通常由一个cookie支持。一些网络表单要求您登录和/或由会话进行跟踪。您可以使用CookieHandler API来维护Cookie。在发送所有HTTP请求之前,您需要准备一个具有ACCEPT_ALLCookiePolicy的CookieManager。

// 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();
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将默认缓冲theentirerequest身体真正发送,无论你使用connection.setRequestProperty(“内容长度”,CONTENTLENGTH)自己设置一个固定内容长度之前;。每当您同时发送大型POST请求(例如上传文件)时,这可能会导致OutOfMemoryException。为了避免这种情况,你想设置HttpURLConnection#setFixedLengthStreamingMode()

httpConnection.setFixedLengthStreamingMode(contentLength);

但是,如果事先不知道内容长度,则可以通过相应地设置HttpURLConnection#setChunkedStreamingMode()来使用分块流模式。这会将HTTPTransfer-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.

使用来自arecent 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()(注意,不是thus****的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网址,也许是因为您正在编写网络抓取工具。在这种情况下,您可能会面临一些HTTPS站点上的javax.net.ssl.SSLException:不受信任的服务器证书,这些HTTPS站点上的SSL证书不会保持最新,或者java.security.cert.CertificateException:在一些错误配置的HTTPS站点上,没有找到与[主机名]找到的主题替代DNS名称匹配或发生javax.net.ssl.SSLProtocolException:握手警报:无法识别的名称。

以下一次性运行在您的网页刮板类中的静态初始化工具应该使得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教程
  • HttpClient示例

###解析并提取HTML

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

  • Java中领先的HTML解析器有哪些优点/缺点?
  • 如何使用Java扫描和提取网页

#2 热门回答(82 赞)

在使用HTTP时,引用HttpURLConnection而不是基类URLConnection几乎总是更有用(因为当您在HTTP URL上请求URLConnection.openConnection()时,URLConnection是一个抽象类,无论如何都会回来的。

那么你可以不用依赖URLConnection#setDoOutput(true)来隐式地设置请求方法为POST,而是执行httpURLConnection.setRequestMethod(“POST”)这可能会更自然一些(也允许你指定其他请求方法如PUT,DELETE,...)。

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

int responseCode = httpURLConnection.getResponseCode();

if (responseCode == HttpURLConnection.HTTP_OK) {

#3 热门回答(47 赞)

受到这个和其他问题的启发,我创建了一个最小的开放源代码,它体现了这里找到的大部分技术。

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


原文链接