如何使用java.net.urlconnection触发和处理http请求?

0tdrvxhp  于 2021-06-30  发布在  Java
关注(0)|答案(7)|浏览(254)

使用 java.net.URLConnection 在这里经常被问到,而oracle教程对它的描述过于简洁。
该教程基本上只展示了如何启动get请求并读取响应。它没有在任何地方解释如何使用它来执行post请求、设置请求头、读取响应头、处理cookie、提交html表单、上载文件等。
那么,我该怎么用 java.net.URLConnection 启动并处理“高级”http请求?

j2datikz

j2datikz1#

更新

新的http客户机与java9一起提供,但是作为名为 jdk.incubator.httpclient . 孵化器模块是一种将非最终API交给开发人员的方法,而这些API在将来的版本中要么最终完成,要么删除。
在Java9中,您可以发送 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;
}
3hvapo4f

3hvapo4f2#

受这个问题和其他问题的启发,我创建了一个最小的开源基本http客户机,它体现了这里发现的大多数技术。
googlehttpjava客户端也是一个很好的开源资源。

ffvjumwh

ffvjumwh3#

我建议您看看kevinsawicki/http请求的代码,它基本上是在 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);
ejk8hzay

ejk8hzay4#

有两个选项可以用于http url点击:get/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);
System.out.println(String.valueOf(http_conn.getResponseCode()));

发布请求:-

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

nbysray55#

首先是事先声明:发布的代码片段都是基本示例。你需要处理一些琐碎的事情 IOException s和 RuntimeException 就像 NullPointerException , ArrayIndexOutOfBoundsException 和你的配偶。

准备

我们首先需要至少知道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 格式和连接方式 & . 通常,您还可以使用指定的字符集对查询参数进行url编码 URLEncoder#encode() .
这个 String#format() 只是为了方便。当我需要字符串连接运算符时,我更喜欢它 + 不止两次。

使用(可选)查询参数触发http get请求

这是一件小事。这是默认的请求方法。

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

任何查询字符串都应该使用 ? . 这个 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。作为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"> 元素,您希望以编程方式“按下”该元素(因为服务器端通常使用该元素来区分是否按下了按钮,如果是,则是哪个按钮)。
你也可以施展获得的技能 URLConnectionHttpURLConnection 使用它的 HttpURLConnection#setRequestMethod() 相反。但是,如果您试图使用输出连接,您仍然需要设置 URLConnection#setDoOutput()true .

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

不管怎样,如果对方是 HttpServlet ,那么 doPost() 方法,参数将由 HttpServletRequest#getParameter() .

实际上触发了http请求

您可以使用 URLConnection#connect() ,但当您希望获取有关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];
            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 维护cookies的api。你需要准备一个 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属性 expires , path 或者,您也可以使用 cookie.substring(0, cookie.indexOf(';')) 而不是 split() .

流模式

这个 HttpURLConnection 默认情况下,将在实际发送请求之前缓冲整个请求体,而不管您是否已使用设置了固定的内容长度 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 将默认设置为 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.keepAlive 系统属性到 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() 方法是相对较新的,它是在Servlet3.0(GlassFish3、Tomcat7等)中引入的。在Servlet3.0之前,最好的选择是使用ApacheCommonsFileUpload来解析 multipart/form-data 请求。关于fileupload和servelt3.0方法的示例,请参见此答案。

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

有时您需要连接https url,可能是因为您正在编写web scraper。在这种情况下,你可能会面临 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 httpcomponents httpclient在这方面要方便得多:)
httpclient教程
httpclient示例

解析和提取html

如果您只想从html解析和提取数据,那么最好使用jsoup之类的html解析器
java中领先的html解析器的优缺点是什么
如何用java扫描和提取网页

6za6bjd0

6za6bjd06#

我也很受这个React的启发。
我经常在我需要做一些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);

}
qncylg1j

qncylg1j7#

在使用http时,参考http几乎总是更有用的 HttpURLConnection 而不是基类 URLConnection (自 URLConnection 是一个抽象类 URLConnection.openConnection() 在一个http网址上,这是你无论如何都会得到的)。
那你就不用依赖 URLConnection#setDoOutput(true) 隐式地将请求方法设置为post而不是do httpURLConnection.setRequestMethod("POST") 有些人可能会觉得更自然(而且还允许您指定其他请求方法,如put、delete等)。
它还提供了有用的http常量,因此您可以执行以下操作:

int responseCode = httpURLConnection.getResponseCode();

if (responseCode == HttpURLConnection.HTTP_OK) {

相关问题