提问



这里经常使用java.net.URLConnection,而Oracle教程太简明扼要。 [137] [138]


该教程基本上只显示了如何触发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格式,并由&连接。您通常也会使用URLEncoder#encode()使用指定的字符集对查询参数进行URL编码。[139] [140]


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





使用(可选)查询参数

触发HTTP GET请求

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


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


任何查询字符串都应使用?连接到URL。 Accept-Charset标题可能会提示服务器参数的编码方式。如果您不发送任何查询字符串,则可以将Accept-Charset标题保留。如果您不需要设置任何标题,然后你甚至可以使用URL#openStream()快捷方法。[142] [143]


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


无论哪种方式,如果另一方是HttpServlet,那么它的doGet()方法将被调用,参数将由HttpServletRequest#getParameter()提供。[144] [145] [[[146]


出于测试目的,您可以将响应主体打印到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,其中查询字符串被写入请求正文。[147] [148]


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[149] [150] [151] [152]


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


无论哪种方式,如果另一方是HttpServlet,那么它的doPost()方法将被调用,参数将由HttpServletRequest#getParameter()提供。[153] [154] [[[155]





实际触发HTTP请求



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





收集HTTP响应信息




  1. HTTP响应状态:[158]


    你需要一个HttpURLConnection。如有必要,先把它扔掉。[159]


    int status = httpConnection.getResponseCode();
    

  2. HTTP响应标头:[160]


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

  3. HTTP响应编码:[161]


    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支持。某些网络表单要求您重新登录和/或通过会话进行跟踪。您可以使用CookieHandler API来维护cookie。您需要使用CookiePolicy准备CookieManager在发送所有HTTP请求之前ACCEPT_ALL[162] [163] [164] [165]


// 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]可以去除与expirespath等服务器端无关的cookie属性。或者,您也可以使用cookie.substring(0, cookie.indexOf(';'))代替[[split()





流媒体模式



默认情况下,HttpURLConnection会在实际发送之前缓冲整个请求正文,无论您是否使用connection.setRequestProperty("Content-Length", contentLength);设置固定内容长度。这可能会导致HttpURLConnection只要你同时发送大的POST请求(例如上传文件),你就可以设置HttpURLConnection#setFixedLengthStreamingMode()[166] [167]


httpConnection.setFixedLengthStreamingMode(contentLength);


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


httpConnection.setChunkedStreamingMode(1024);





的User-Agent



可能会发生请求返回意外响应,而它可以在真正的Web浏览器中正常工作。服务器端可能会根据User-Agent请求标头阻止请求。 URLConnection默认将其设置为Java/1.6.0_19,其中最后一部分显然是JRE版本。您可以按如下方式覆盖: [171]


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.


使用最近浏览器中的User-Agent字符串。[172]





错误处理



如果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中有更详细的描述。[173] [174]


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方法的示例。[175] [176] [177] [178]





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



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


您的Web scraper类中的以下一次性运行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 很多更方便:)[180]



  • HttpClient教程

  • HttpClient示例






解析和提取HTML



如果您只需要从HTML解析和提取数据,那么最好使用像Jsoup [181] [182] [183]​​]]这样的HTML解析器



  • Java中领先的HTML解析器的优缺点是什么

  • 如何使用Java扫描和提取网页


其它参考1


当使用HTTP时,引用HttpURLConnection而不是基类URLConnection几乎总是更有用(因为URLConnection是一个抽象类,当你要求URLConnection.openConnection()时一个HTTP URL,无论如何你都会得到它。)


然后你可以而不是依赖URLConnection#setDoOutput(true)来隐式地将请求方法设置为 POST 而不是httpURLConnection.setRequestMethod("POST"),有些人可能会发现更自然(并且还允许您指定其他请求)诸如 PUT , DELETE ,...)之类的方法。


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


int responseCode = httpURLConnection.getResponseCode();

if (responseCode == HttpURLConnection.HTTP_OK) {

其它参考2


受SO和其他问题的启发,我创建了一个最小的开源基本-http-client,它体现了这里发现的大多数技术。[186]


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

其它参考3


HTTP URL Hits有两个选项: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()));

其它参考4


我建议你看一下kevinsawicki/http-request上的代码,它基本上是HttpUrlConnection之上的包装器,它提供了一个更简单的API,以防你只是想立即发出请求或者你可以采取一个看一下来源(它不是太大)来看看如何处理连接。[188]


示例:使用内容类型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);

其它参考5


我也对这种反应非常鼓舞。


我经常在我需要做一些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[189]


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

其它参考6


更新




  新的HTTP客户端随Java 9一起提供,但作为一部分
  孵化器模块名为jdk.incubator.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.incubator.httpclient模块中,因此应在module-info.java文件中声明此依赖关系:


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

其它参考7


最初我被这篇赞成HttpClient的文章误导了。 [190]


后来我意识到HttpURLConnection将不再是这篇文章[191]


根据Google博客:



  Apache HTTP客户端在Eclair和Froyo上的错误更少。它是这些版本的最佳选择。对于Gingerbread,HttpURLConnection是最佳选择。其简单的API和小巧的尺寸使其非常适合Android。

  
  透明的压缩和响应缓存减少了网络使用,提高了速度并节省了电池。新的应用程序应该使用HttpURLConnection;这是我们将继续投入精力的地方。



在阅读了本文和其他一些关于流动问题的文章后,我确信HttpURLConnection会持续更长的时间。[192]


一些有利于HttpURLConnections的SE问题:


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


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

其它参考8


您也可以使用jcabi-http(我是开发人员)的JdkRequest,它可以为您完成所有这些工作,装饰HttpURLConnection,触发HTTP请求和解析响应,例如:[195] [196]]]


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


查看此博客文章了解更多信息:http://www.yegor256.com/2014/04/11/jcabi-http-intro.html [187]

其它参考9


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



  

      
  • HTTP/2支持允许对同一主机的所有请求共享套接字。

  •   
  • 连接池减少了请求延迟(如果HTTP/2不可用)。

  •   
  • 透明GZIP缩小了下载大小。

  •   
  • 响应缓存可以完全避免网络重复请求。

  •   



首先创建OkHttpClient的实例:


OkHttpClient client = new OkHttpClient();


然后,准备你的GET请求:


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


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


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


有关更多详细信息,请参阅OkHttp的文档[199]

其它参考10


如果您使用http get请删除此行


urlConnection.setDoOutput(true);