Use of URLConnection is asked about pretty often here, and the Oracle tutorial is too concise about it. So how do I use it to initiate and handle HTTP requests?
Are there other hints, and "best practices" for this, that may be useful?
home / developersection / forums / using java.net.urlconnection to fire and handle http requests?
Use of URLConnection is asked about pretty often here, and the Oracle tutorial is too concise about it. So how do I use it to initiate and handle HTTP requests?
Are there other hints, and "best practices" for this, that may be useful?
Anonymous User
06-May-2015for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {System.out.println(header.getKey() + "=" + header.getValue());
}
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.
}
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401"); // Do as if you're using Firefox 3.6.3.System.setProperty("http.keepAlive", "false");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);
}
}