// 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();// ...
// 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]);}// ...
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.
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();}
有时您需要连接一个HTTPS URL,可能是因为您正在编写一个网页刮刀。在这种情况下,您可能会在某些HTTPS站点上遇到javax.net.ssl.SSLException: Not trusted server certificate,这些站点没有保持其SSL证书最新,或者在一些配置错误的HTTPS站点上遇到java.security.cert.CertificateException: No subject alternative DNS name matching [hostname] found或javax.net.ssl.SSLProtocolException: handshake alert: unrecognized_name。
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());