这里经常会问到java.net.URLConnection的使用,Oracle教程对此过于简洁。

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

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


事先先声明:发布的代码片段都是基本示例。您将需要处理微不足道的IOExceptions和RuntimeExceptions,如NullPointerException、ArrayIndexOutOfBoundsException和自己的协同工作。

如果您开发的是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));

查询参数必须采用名称=值格式,并由&连接。通常还可以使用URLEncoder#encoder()使用指定的字符集对查询参数进行URL编码。

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


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

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

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

任何查询字符串都应使用?连接到URL?。Accept-Charset标头可能会提示服务器参数的编码方式。如果您不发送任何查询字符串,则可以不发送Accept-Ccharset标头。如果您不需要设置任何标头,那么您甚至可以使用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表单时,不要忘记将任何<input type=“hidden”>元素的name=value对放入查询字符串中,当然也要将<input type=“submit”>元素中的name=值对放入您希望以编程方式“按下”的元素中(因为这通常在服务器端用于区分是否按下了按钮,如果按下了,则是哪个按钮)。

还可以将获得的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响应编码:

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

    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,其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头。基本上,您需要从登录或第一个GET请求的响应中获取所有SetCookie标头,然后将其传递给后续请求。

// 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属性,如过期、路径等。或者,也可以使用cookie.substring(0,cookie.indexOf(';'))代替split()。


流式处理模式

默认情况下,HttpURLConnection将在实际发送请求之前缓冲整个请求体,无论您是否使用connection.setRequestProperty(“content-length”,contentLength);自己设置了固定的内容长度;。每当您同时发送大型POST请求(例如上载文件)时,这可能会导致OutOfMemoryExceptions。为了避免这种情况,您需要设置HttpURLConnection#setFixedLengthStreamingMode()。

httpConnection.setFixedLengthStreamingMode(contentLength);

但如果内容长度确实事先不知道,那么可以通过相应地设置HttpURLConnection#setChunkedStreamingMode()来使用分块流模式。这将将HTTP传输编码头设置为分块,这将强制将请求正文分块发送。下面的示例将以1KB的块发送正文。

httpConnection.setChunkedStreamingMode(1024);

用户代理

请求可能会返回意外的响应,而它在真实的web浏览器中工作正常。服务器端可能正在基于用户代理请求标头阻止请求。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.kkeepAlive系统属性设置为false来关闭它。您可以通过以下方式在应用程序开始时以编程方式执行此操作:

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

正在上载文件

您通常会对混合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解析多部分/表单数据请求。关于FileUpload和Servelt 3.0方法的示例,请参见此答案。


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

如果您开发的是Android而不是Java,请注意:如果您在开发过程中没有部署正确的证书,下面的解决方法可能会节省您的一天。但您不应将其用于生产。这些天(2021 4月),如果谷歌检测到不安全的主机名验证器,他们将不允许你的应用程序在Play Store上发布,请参阅https://support.google.com/faqs/answer/7188426.

有时您需要连接一个HTTPS URL,可能是因为您正在编写一个web scraper。在这种情况下,您可能会遇到javax.net.ssl.SSLException:某些HTTPS站点上不受信任的服务器证书,这些站点的ssl证书没有保持最新,或者java.security.cert.CertificateException:找不到与[主机名]匹配的主题替代DNS名称,或者javax.net.ssl.SSLProtocolException:握手警告:某些配置错误的HTTPS站点上无法识别的名称。

web scraper类中的以下一次性运行静态初始值设定项应使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中解析和提取数据,那么最好使用Jsoup这样的HTML解析器。

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


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

然后,您可以不依赖URLConnection#setDoOutput(true)将请求方法隐式设置为POST,而是使用httpURLConnection.setRequestMethod(“POST”),有些人可能会觉得这更自然(这也允许您指定其他请求方法,如PUT、DELETE…)。

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

int responseCode = httpURLConnection.getResponseCode();

if (responseCode == HttpURLConnection.HTTP_OK) {

受Stack Overflow的这些问题和其他问题的启发,我创建了一个最小的开源基本http客户端,它体现了这里找到的大多数技术。

googlehttpjava客户端也是一个很好的开源资源。


我也受到了这个回应的启发。

我经常在需要做一些HTTP的项目中,我可能不想引入很多第三方依赖关系(这会引入其他依赖关系等等)

我开始根据这段对话编写我自己的实用程序(没有在任何地方完成):

package org.boon.utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

import static org.boon.utils.IO.read;

public class HTTP {

然后就是一堆静态方法。

public static String get(
        final String url) {

    Exceptions.tryIt(() -> {
        URLConnection connection;
        connection = doGet(url, null, null, null);
        return extractResponseString(connection);
    });
    return null;
}

public static String getWithHeaders(
        final String url,
        final Map<String, ? extends Object> headers) {
    URLConnection connection;
    try {
        connection = doGet(url, headers, null, null);
        return extractResponseString(connection);
    } catch (Exception ex) {
        Exceptions.handle(ex);
        return null;
    }
}

public static String getWithContentType(
        final String url,
        final Map<String, ? extends Object> headers,
        String contentType) {
    URLConnection connection;
    try {
        connection = doGet(url, headers, contentType, null);
        return extractResponseString(connection);
    } catch (Exception ex) {
        Exceptions.handle(ex);
        return null;
    }
}
public static String getWithCharSet(
        final String url,
        final Map<String, ? extends Object> headers,
        String contentType,
        String charSet) {
    URLConnection connection;
    try {
        connection = doGet(url, headers, contentType, charSet);
        return extractResponseString(connection);
    } catch (Exception ex) {
        Exceptions.handle(ex);
        return null;
    }
}

然后发布。。。

public static String postBody(
        final String url,
        final String body) {
    URLConnection connection;
    try {
        connection = doPost(url, null, "text/plain", null, body);
        return extractResponseString(connection);
    } catch (Exception ex) {
        Exceptions.handle(ex);
        return null;
    }
}

public static String postBodyWithHeaders(
        final String url,
        final Map<String, ? extends Object> headers,
        final String body) {
    URLConnection connection;
    try {
        connection = doPost(url, headers, "text/plain", null, body);
        return extractResponseString(connection);
    } catch (Exception ex) {
        Exceptions.handle(ex);
        return null;
    }
}


public static String postBodyWithContentType(
        final String url,
        final Map<String, ? extends Object> headers,
        final String contentType,
        final String body) {

    URLConnection connection;
    try {
        connection = doPost(url, headers, contentType, null, body);

        return extractResponseString(connection);

    } catch (Exception ex) {
        Exceptions.handle(ex);
        return null;
    }

}


public static String postBodyWithCharset(
        final String url,
        final Map<String, ? extends Object> headers,
        final String contentType,
        final String charSet,
        final String body) {

    URLConnection connection;
    try {
        connection = doPost(url, headers, contentType, charSet, body);

        return extractResponseString(connection);

    } catch (Exception ex) {
        Exceptions.handle(ex);
        return null;
    }
}

private static URLConnection doPost(String url, Map<String, ? extends Object> headers,
                                    String contentType, String charset, String body
                                    ) throws IOException {
    URLConnection connection;/* Handle output. */
    connection = new URL(url).openConnection();
    connection.setDoOutput(true);
    manageContentTypeHeaders(contentType, charset, connection);

    manageHeaders(headers, connection);

    IO.write(connection.getOutputStream(), body, IO.CHARSET);
    return connection;
}

private static void manageHeaders(Map<String, ? extends Object> headers, URLConnection connection) {
    if (headers != null) {
        for (Map.Entry<String, ? extends Object> entry : headers.entrySet()) {
            connection.setRequestProperty(entry.getKey(), entry.getValue().toString());
        }
    }
}

private static void manageContentTypeHeaders(String contentType, String charset, URLConnection connection) {
    connection.setRequestProperty("Accept-Charset", charset == null ? IO.CHARSET : charset);
    if (contentType!=null && !contentType.isEmpty()) {
        connection.setRequestProperty("Content-Type", contentType);
    }
}

private static URLConnection doGet(String url, Map<String, ? extends Object> headers,
                                    String contentType, String charset) throws IOException {
    URLConnection connection;/* Handle output. */
    connection = new URL(url).openConnection();
    manageContentTypeHeaders(contentType, charset, connection);

    manageHeaders(headers, connection);

    return connection;
}

private static String extractResponseString(URLConnection connection) throws IOException {
/* Handle input. */
    HttpURLConnection http = (HttpURLConnection)connection;
    int status = http.getResponseCode();
    String charset = getCharset(connection.getHeaderField("Content-Type"));

    if (status==200) {
        return readResponseBody(http, charset);
    } else {
        return readErrorResponseBody(http, status, charset);
    }
}

private static String readErrorResponseBody(HttpURLConnection http, int status, String charset) {
    InputStream errorStream = http.getErrorStream();
    if ( errorStream!=null ) {
        String error = charset== null ? read( errorStream ) :
            read( errorStream, charset );
        throw new RuntimeException("STATUS CODE =" + status + "\n\n" + error);
    } else {
        throw new RuntimeException("STATUS CODE =" + status);
    }
}

private static String readResponseBody(HttpURLConnection http, String charset) throws IOException {
    if (charset != null) {
        return read(http.getInputStream(), charset);
    } else {
        return read(http.getInputStream());
    }
}

private static String getCharset(String contentType) {
    if (contentType==null)  {
        return null;
    }
    String charset = null;
    for (String param : contentType.replace(" ", "").split(";")) {
        if (param.startsWith("charset=")) {
            charset = param.split("=", 2)[1];
            break;
        }
    }
    charset = charset == null ? IO.CHARSET : charset;

    return charset;
}

嗯,你明白了。。。。

以下是测试:

static class MyHandler implements HttpHandler {
    public void handle(HttpExchange t) throws IOException {

        InputStream requestBody = t.getRequestBody();
        String body = IO.read(requestBody);
        Headers requestHeaders = t.getRequestHeaders();
        body = body + "\n" + copy(requestHeaders).toString();
        t.sendResponseHeaders(200, body.length());
        OutputStream os = t.getResponseBody();
        os.write(body.getBytes());
        os.close();
    }
}


@Test
public void testHappy() throws Exception {

    HttpServer server = HttpServer.create(new InetSocketAddress(9212), 0);
    server.createContext("/test", new MyHandler());
    server.setExecutor(null); // creates a default executor
    server.start();

    Thread.sleep(10);

    Map<String,String> headers = map("foo", "bar", "fun", "sun");

    String response = HTTP.postBodyWithContentType("http://localhost:9212/test", headers, "text/plain", "hi mom");

    System.out.println(response);

    assertTrue(response.contains("hi mom"));
    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));

    response = HTTP.postBodyWithCharset("http://localhost:9212/test", headers, "text/plain", "UTF-8", "hi mom");

    System.out.println(response);

    assertTrue(response.contains("hi mom"));
    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));

    response = HTTP.postBodyWithHeaders("http://localhost:9212/test", headers, "hi mom");

    System.out.println(response);

    assertTrue(response.contains("hi mom"));
    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));

    response = HTTP.get("http://localhost:9212/test");

    System.out.println(response);

    response = HTTP.getWithHeaders("http://localhost:9212/test", headers);

    System.out.println(response);

    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));

    response = HTTP.getWithContentType("http://localhost:9212/test", headers, "text/plain");

    System.out.println(response);

    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));

    response = HTTP.getWithCharSet("http://localhost:9212/test", headers, "text/plain", "UTF-8");

    System.out.println(response);

    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));

    Thread.sleep(10);

    server.stop(0);
}

@Test
public void testPostBody() throws Exception {

    HttpServer server = HttpServer.create(new InetSocketAddress(9220), 0);
    server.createContext("/test", new MyHandler());
    server.setExecutor(null); // creates a default executor
    server.start();

    Thread.sleep(10);

    Map<String,String> headers = map("foo", "bar", "fun", "sun");

    String response = HTTP.postBody("http://localhost:9220/test", "hi mom");

    assertTrue(response.contains("hi mom"));

    Thread.sleep(10);

    server.stop(0);
}

@Test(expected = RuntimeException.class)
public void testSad() throws Exception {

    HttpServer server = HttpServer.create(new InetSocketAddress(9213), 0);
    server.createContext("/test", new MyHandler());
    server.setExecutor(null); // creates a default executor
    server.start();

    Thread.sleep(10);

    Map<String,String> headers = map("foo", "bar", "fun", "sun");

    String response = HTTP.postBodyWithContentType("http://localhost:9213/foo", headers, "text/plain", "hi mom");

    System.out.println(response);

    assertTrue(response.contains("hi mom"));
    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));

    Thread.sleep(10);

    server.stop(0);
}

您可以在此处找到其余内容:

https://github.com/RichardHightower/boon

我的目标是以一种更简单的方式提供人们想要做的常见事情。。。。


您还可以使用jcabi http(我是一名开发人员)的JdkRequest,它为您完成所有这些工作,装饰HttpURLConnection、激发http请求和解析响应,例如:

String html = new JdkRequest("http://www.google.com").fetch().body();

查看此日志以了解更多信息:http://www.yegor256.com/2014/04/11/jcabi-http-intro.html


我建议你看一下kevinsawicki/http请求的代码,它基本上是HttpUrlConnection之上的一个包装器,它提供了一个简单得多的API,以防你现在只想发出请求,或者你可以看一下源代码(不太大),看看连接是如何处理的。

示例:使用内容类型application/json和一些查询参数发出GET请求:

// GET http://google.com?q=baseball%20gloves&size=100
String response = HttpRequest.get("http://google.com", true, "q", "baseball gloves", "size", 100)
        .accept("application/json")
        .body();
System.out.println("Response was: " + response);

HTTP URL命中有两个选项:GET/POST

GET请求:

HttpURLConnection.setFollowRedirects(true); // Defaults to true

String url = "https://name_of_the_url";
URL request_url = new URL(url);
HttpURLConnection http_conn = (HttpURLConnection)request_url.openConnection();
http_conn.setConnectTimeout(100000);
http_conn.setReadTimeout(100000);
http_conn.setInstanceFollowRedirects(true);
System.out.println(String.valueOf(http_conn.getResponseCode()));

POST请求:

HttpURLConnection.setFollowRedirects(true); // Defaults to true

String url = "https://name_of_the_url"
URL request_url = new URL(url);
HttpURLConnection http_conn = (HttpURLConnection)request_url.openConnection();
http_conn.setConnectTimeout(100000);
http_conn.setReadTimeout(100000);
http_conn.setInstanceFollowRedirects(true);
http_conn.setDoOutput(true);
PrintWriter out = new PrintWriter(http_conn.getOutputStream());
if (urlparameter != null) {
   out.println(urlparameter);
}
out.close();
out = null;
System.out.println(String.valueOf(http_conn.getResponseCode()));

最初,我被这篇有利于HttpClient的文章误导了。

后来,我意识到HttpURLConnection将继续留在本文中。

根据谷歌博客:

Apache HTTP客户端在Eclair和Froyo上的bug更少。这是这些版本的最佳选择。对于姜饼,HttpURLConnection是最佳选择。其简单的API和小巧的尺寸使其非常适合Android。透明压缩和响应缓存减少了网络使用,提高了速度并节省了电池。新应用程序应使用HttpURLConnection;这是我们今后将花费精力的地方。

在阅读了这篇文章和一些其他堆栈流问题之后,我确信HttpURLConnection将持续更长的时间。

支持HttpURLConnection的一些SE问题:

在Android上,使用URL编码表单数据进行POST请求,而不使用UrlEncodedFormEntity

HttpPost适用于Java项目,但不适用于Android


还有OkHttp,它是一个默认高效的HTTP客户端:

HTTP/2支持允许对同一主机的所有请求共享一个套接字。连接池减少了请求延迟(如果HTTP/2不可用)。透明GZIP缩小了下载大小。响应缓存完全避免了重复请求的网络。

首先创建OkHttpClient的实例:

OkHttpClient client = new OkHttpClient();

然后,准备GET请求:

Request request = new Request.Builder()
      .url(url)
      .build();

最后,使用OkHttpClient发送准备好的请求:

Response response = client.newCall(request).execute();

有关详细信息,请参阅OkHttp的文档


如果您使用的是HTTP GET,请删除此行:

urlConnection.setDoOutput(true);

使现代化

新的HTTP客户端随Java 9一起提供,但作为孵化器模块名为jdk.incluator.httpclient。孵化器模块包括一种将非最终API交给开发人员的方法API在未来定稿或删除方面的进展释放

在Java 9中,您可以发送GET请求,如:

// GET
HttpResponse response = HttpRequest
    .create(new URI("http://www.stackoverflow.com"))
    .headers("Foo", "foovalue", "Bar", "barvalue")
    .GET()
    .response();

然后可以检查返回的HttpResponse:

int statusCode = response.statusCode();
String responseBody = response.body(HttpResponse.asString());

由于这个新的HTTP客户端位于java.httpclient-jdk.wirculator.httpclient模块中,您应该在module-info.java文件中声明这个依赖关系:

module com.foo.bar {
    requires jdk.incubator.httpclient;
}

如果您使用的是Java 11(Android除外),而不是传统的HttpUrlConnection类,则可以使用Java 11新的HTTP客户端API。

GET请求示例:

var uri = URI.create("https://httpbin.org/get?age=26&isHappy=true");
var client = HttpClient.newHttpClient();
var request = HttpRequest
        .newBuilder()
        .uri(uri)
        .header("accept", "application/json")
        .GET()
        .build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());

异步执行的同一请求:

var responseAsync = client
        .sendAsync(request, HttpResponse.BodyHandlers.ofString())
        .thenApply(HttpResponse::body)
        .thenAccept(System.out::println);
// responseAsync.join(); // Wait for completion

POST请求示例:

var request = HttpRequest
        .newBuilder()
        .uri(uri)
        .version(HttpClient.Version.HTTP_2)
        .timeout(Duration.ofMinutes(1))
        .header("Content-Type", "application/json")
        .header("Authorization", "Bearer fake")
        .POST(BodyPublishers.ofString("{ title: 'This is cool' }"))
        .build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());

要以多部分(multipart/form-data)或url编码(application/x-www-form-urlencoded)格式发送表单数据,请参阅此解决方案。

有关HTTP客户端API的示例和更多信息,请参阅本文。

旁注

对于Java标准库HTTP服务器,请参阅本文。