Stringurl="http://example.com"; Stringcharset="UTF-8"; // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name() Stringparam1="value1"; Stringparam2="value2"; // ...
// First set the default cookie manager. CookieHandler.setDefault(newCookieManager(null, CookiePolicy.ACCEPT_ALL));
// All the following subsequent URLConnections will use the same cookie manager. URLConnectionconnection=newURL(url).openConnection(); // ...
connection = newURL(url).openConnection(); // ...
connection = newURL(url).openConnection(); // ...
若上述方法不起作用,可手动收集和设置Cookie头。
1 2 3 4 5 6 7 8 9 10 11
// Gather all cookies on the first request. URLConnectionconnection=newURL(url).openConnection(); List<String> cookies = connection.getHeaderFields().get("Set-Cookie"); // ...
// Then use the same cookies on all subsequent requests. connection = newURL(url).openConnection(); for (String cookie : cookies) { connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]); } // ...
// 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(); }
static { TrustManager[] trustAllCertificates = newTrustManager[] { newX509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { returnnull; // Not relevant. } @Override publicvoidcheckClientTrusted(X509Certificate[] certs, String authType) { // Do nothing. Just allow them all. } @Override publicvoidcheckServerTrusted(X509Certificate[] certs, String authType) { // Do nothing. Just allow them all. } } };
HostnameVerifiertrustAllHostnames=newHostnameVerifier() { @Override publicbooleanverify(String hostname, SSLSession session) { returntrue; // Just allow them all. } };