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


1945

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

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

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

Answers:


2710

首先先声明一下:发布的代码段都是基本示例。您需要处理琐碎的IOExceptions和RuntimeExceptions like 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()

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

无论哪种方式,如果另一侧是a 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");
// ...

无论哪种方式,如果另一侧是a HttpServlet,则将doPost()调用其方法,并且参数将通过提供HttpServletRequest#getParameter()


实际触发HTTP请求

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


收集HTTP响应信息

  1. HTTP响应状态

    您需要HttpURLConnection这里。如有必要,请先投放。

    int status = httpConnection.getResponseCode();
  2. HTTP响应标头

    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        System.out.println(header.getKey() + "=" + header.getValue());
    }
  3. 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];
            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表单要求您登录和/或由会话跟踪。您可以使用CookieHandlerAPI维护cookie。你需要准备一个CookieManager具有CookiePolicyACCEPT_ALL发送所有HTTP请求之前。

// 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默认情况下,will会在实际发送请求之前缓冲整个请求正文,无论您是否使用设置了固定的内容长度connection.setRequestProperty("Content-Length", contentLength);OutOfMemoryException每当您同时发送大型POST请求(例如,上传文件)时,这可能会导致。为避免这种情况,您想设置HttpURLConnection#setFixedLengthStreamingMode()

httpConnection.setFixedLengthStreamingMode(contentLength);

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

httpConnection.setChunkedStreamingMode(1024);

用户代理

请求可能会返回意外响应,而在真正的Web浏览器中却可以正常工作。服务器端可能正在根据User-Agent请求标头阻止请求。URLConnection默认情况下,will将其设置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.

使用最新浏览器中的User-Agent字符串。


错误处理

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

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

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

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

上载档案

通常,multipart/form-data对混合的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解析multipart/form-data请求。另请参见此答案,以获取FileUpload和Servelt 3.0方法的示例。


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

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

static您的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的HttpClient的HttpComponents多少这一切更方便:)


解析和提取HTML

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


119
您应该先放置apache链接,这样人们才能找到解决方案的速度更快;)
ZeissS 2010年

40
@ivanceras:如果您不能根据此答案中的信息将其简化,请按Ask Question右上方的按钮。
BalusC

3
@布雷斯:请阅读规格。该--部分不是边界本身的一部分。这只是一个分隔符字符串。我已回滚您的无效修改。
BalusC 2012年

7
@BalusC非常感谢您提供了如此完美的教程。还请包括“关闭流/连接”之类的标题。我真的很困惑何时关闭哪个流/连接。

10
可悲的是,在Android上,建议立即使用Apache HttpClient,这HttpURLConnection很残酷。android-developers.blogspot.in/2011/09/...
亚提sagade

91

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

然后,您可以不用依赖于URLConnection#setDoOutput(true)将请求方法隐式设置为POST,而可以做httpURLConnection.setRequestMethod("POST")一些可能更自然的事情(并且还可以指定其他请求方法,例如PUTDELETE,...)。

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

int responseCode = httpURLConnection.getResponseCode();

if (responseCode == HttpURLConnection.HTTP_OK) {

1
setDoOutPut true是我的问题,将我的GET设置为POST。谢谢
Patrick Kafka

22
如果您尝试将数据写入输出流,则仍必须设置setDoOutput()为,true否则会引发异常(即使您是setRequestMethod("POST"))。明确说明:设置URLConnection#setDoOutput(true)true隐式将请求方法设置httpURLConnection.setRequestMethod("POST")为POST ,但设置为POST则没有隐式设置setDoOutput()true
Tony Chan

54

受这个问题以及关于SO的其他问题的启发,我创建了一个最小的开源basic-http-client,体现了此处找到的大多数技术。

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


我只是在想同样的事情。但是,拥有一个准系统/简单的Java库(仅使用此处提供的URLConnection代码)也可能会很好,该代码将代码封装为更简单的方法以执行HTTP GET,POST等。然后可以将该库编译并打包为JAR和如果不需要外部JAR,则可以在Java项目中包括以Java代码或源类文件导入/使用的Java项目。可以使用其他库(例如Apache等)来完成此操作,但是与使用URLConnection的简单1文件类库相比,这更麻烦。
David


24

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

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

// 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);

24

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()));

3
您如何查看实际的JSON响应?
索拉

21

这个回应也给我很大的启发。

我经常在需要执行一些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

我的目标是以一种比...更简单的方式提供人们想做的普通事情。


2
奇怪的是,该doPost方法中有一个charset用于设置请求标头的参数,但是随后使用一些硬编码的字符集写入数据IO.CHARSET。有毛病吗
Vit Khudenko

21

更新资料

新的HTTP客户端随Java 9一起提供,但作为名为Incubator模块的一部分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;
}

1
进一步更新:模块已脱离孵化状态。现在是java.net.http,而不是jdk.incubator.httpclient。
VGR

17

最初我被这篇赞成的文章误导了HttpClient

后来我意识到,HttpURLConnection这篇文章将保留这一点。

根据Google博客

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

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

在阅读了本文和其他一些有关流程的问题之后,我相信它将HttpURLConnection持续更长的时间。

一些SE问题青睐HttpURLConnections

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

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


15

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

  • 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的文档。



By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.