List of usage examples for java.net HttpURLConnection getHeaderField
public String getHeaderField(int n)
From source file:Main.java
/** * On some devices we have to hack://from w w w . j a v a 2 s .c om * http://developers.sun.com/mobility/reference/techart/design_guidelines/http_redirection.html * @return the resolved url if any. Or null if it couldn't resolve the url * (within the specified time) or the same url if response code is OK */ public static String getResolvedUrl(String urlAsString, int timeout) { try { URL url = new URL(urlAsString); //using proxy may increase latency HttpURLConnection hConn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY); // force no follow hConn.setInstanceFollowRedirects(false); // the program doesn't care what the content actually is !! // http://java.sun.com/developer/JDCTechTips/2003/tt0422.html hConn.setRequestMethod("HEAD"); // default is 0 => infinity waiting hConn.setConnectTimeout(timeout); hConn.setReadTimeout(timeout); hConn.connect(); int responseCode = hConn.getResponseCode(); hConn.getInputStream().close(); if (responseCode == HttpURLConnection.HTTP_OK) return urlAsString; String loc = hConn.getHeaderField("Location"); if (responseCode == HttpURLConnection.HTTP_MOVED_PERM && loc != null) return loc.replaceAll(" ", "+"); } catch (Exception ex) { } return ""; }
From source file:io.github.bonigarcia.wdm.Downloader.java
public static final synchronized void download(URL url, String version, String export, List<String> driverName) throws IOException { File targetFile = new File(getTarget(version, url)); File binary = null;// www .j ava 2 s . c o m // Check if binary exists boolean download = !targetFile.getParentFile().exists() || (targetFile.getParentFile().exists() && targetFile.getParentFile().list().length == 0) || WdmConfig.getBoolean("wdm.override"); if (!download) { // Check if existing binary is valid Collection<File> listFiles = FileUtils.listFiles(targetFile.getParentFile(), null, true); for (File file : listFiles) { for (String s : driverName) { if (file.getName().startsWith(s) && file.canExecute()) { binary = file; log.debug("Using binary driver previously downloaded {}", binary); download = false; break; } else { download = true; } } if (!download) { break; } } } if (download) { log.info("Downloading {} to {}", url, targetFile); HttpURLConnection conn = getConnection(url); int responseCode = conn.getResponseCode(); log.debug("Response HTTP {}", responseCode); if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_SEE_OTHER) { // HTTP Redirect URL newUrl = new URL(conn.getHeaderField("Location")); log.debug("Redirect to {}", newUrl); conn = getConnection(newUrl); } FileUtils.copyInputStreamToFile(conn.getInputStream(), targetFile); if (!export.contains("edge")) { binary = extract(targetFile, export); targetFile.delete(); } else { binary = targetFile; } } if (export != null) { BrowserManager.exportDriver(export, binary.toString()); } }
From source file:org.blockartistry.mod.DynSurround.VersionCheck.java
private static void versionCheck() { try {/*ww w . jav a 2s . com*/ String location = REMOTE_VERSION_FILE; HttpURLConnection conn = null; while (location != null && !location.isEmpty()) { URL url = new URL(location); if (conn != null) { conn.disconnect(); } conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; ru; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11 (.NET CLR 3.5.30729)"); conn.connect(); location = conn.getHeaderField("Coordinates"); } if (conn == null) { throw new NullPointerException(); } BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null) { String[] tokens = line.split(":"); if (mcVersion.matches(tokens[0])) { currentVersion = new SoftwareVersion(tokens[1]); break; } } status = UpdateStatus.CURRENT; if (modVersion.compareTo(currentVersion) < 0) status = UpdateStatus.OUTDATED; conn.disconnect(); reader.close(); } catch (Exception e) { ModLog.warn("Unable to read remote version data", e); status = UpdateStatus.COMM_ERROR; } }
From source file:org.blockartistry.mod.Restructured.VersionCheck.java
private static void versionCheck() { try {/*w ww.j a va2 s. c o m*/ String location = REMOTE_VERSION_FILE; HttpURLConnection conn = null; while (location != null && !location.isEmpty()) { URL url = new URL(location); if (conn != null) { conn.disconnect(); } conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; ru; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11 (.NET CLR 3.5.30729)"); conn.connect(); location = conn.getHeaderField("Location"); } if (conn == null) { throw new NullPointerException(); } BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null) { String[] tokens = line.split(":"); if (mcVersion.matches(tokens[0])) { currentVersion = new SoftwareVersion(tokens[1]); break; } } status = UpdateStatus.CURRENT; if (modVersion.compareTo(currentVersion) < 0) status = UpdateStatus.OUTDATED; conn.disconnect(); reader.close(); } catch (Exception e) { ModLog.warn("Unable to read remote version data", e); status = UpdateStatus.COMM_ERROR; } }
From source file:com.google.android.apps.gutenberg.provider.SyncAdapter.java
private static String getCookie(String authToken) throws IOException { HttpURLConnection connection = null; try {//from w w w .ja v a 2 s . c om connection = (HttpURLConnection) new URL( BuildConfig.HOST + "/_ah/login?continue=http://localhost/&auth=" + authToken).openConnection(); connection.setInstanceFollowRedirects(false); connection.connect(); if (connection.getResponseCode() != 302) { Log.e(TAG, "Cannot fetch the cookie: " + connection.getResponseCode()); return null; } String cookie = connection.getHeaderField("Set-Cookie"); if (!cookie.contains("SACSID")) { return null; } return cookie; } finally { if (connection != null) { connection.disconnect(); } } }
From source file:com.cloud.utils.UriUtils.java
public static Long getRemoteSize(String url) { Long remoteSize = (long) 0; HttpURLConnection httpConn = null; HttpsURLConnection httpsConn = null; try {/*from ww w. ja va 2s. c om*/ URI uri = new URI(url); if (uri.getScheme().equalsIgnoreCase("http")) { httpConn = (HttpURLConnection) uri.toURL().openConnection(); if (httpConn != null) { httpConn.setConnectTimeout(2000); httpConn.setReadTimeout(5000); String contentLength = httpConn.getHeaderField("content-length"); if (contentLength != null) { remoteSize = Long.parseLong(contentLength); } httpConn.disconnect(); } } else if (uri.getScheme().equalsIgnoreCase("https")) { httpsConn = (HttpsURLConnection) uri.toURL().openConnection(); if (httpsConn != null) { String contentLength = httpsConn.getHeaderField("content-length"); if (contentLength != null) { remoteSize = Long.parseLong(contentLength); } httpsConn.disconnect(); } } } catch (URISyntaxException e) { throw new IllegalArgumentException("Invalid URL " + url); } catch (IOException e) { throw new IllegalArgumentException("Unable to establish connection with URL " + url); } return remoteSize; }
From source file:Main.java
public static String executePost(String targetURL, String urlParameters) { try {//www .j av a 2s. c om HttpURLConnection connection = (HttpURLConnection) new URL(targetURL).openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); //connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStream output = null; try { output = connection.getOutputStream(); output.write(urlParameters.getBytes()); } finally { if (output != null) try { output.flush(); output.close(); } catch (IOException logOrIgnore) { } } InputStream response = connection.getInputStream(); String contentType = connection.getHeaderField("Content-Type"); String responseStr = ""; if (true) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(response)); for (String line; (line = reader.readLine()) != null;) { //System.out.println(line); responseStr = responseStr + line; Thread.sleep(2); } } finally { if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) { } } } else { // It's likely binary content, use InputStream/OutputStream. System.out.println("Binary content"); } return responseStr; } catch (Exception e) { e.printStackTrace(); } return ""; }
From source file:edu.hackathon.perseus.core.httpSpeedTest.java
public static String getRedirectUrl(REGION region) { String result = ""; switch (region) { case EU:// w w w . j a v a 2 s . co m result = amazonEuDomain; break; case USA: result = amazonUsaDomain; break; case ASIA: result = amazonAsiaDomain; break; } System.out.println("Trying to get real IP address of " + result); try { /* HttpHead headRequest = new HttpHead(result); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(headRequest); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { String location = response.getHeaders("Location")[0].toString(); String redirecturl = location.replace("Location: ", ""); result = redirecturl; } */ URL url = new URL(result); HttpURLConnection httpGetCon = (HttpURLConnection) url.openConnection(); httpGetCon.setInstanceFollowRedirects(false); httpGetCon.setRequestMethod("GET"); httpGetCon.setConnectTimeout(5000); //set timeout to 5 seconds httpGetCon.setRequestProperty("User-Agent", USER_AGENT); int status = httpGetCon.getResponseCode(); System.out.println("code: " + status); if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) result = httpGetCon.getHeaderField("Location"); } catch (Exception e) { System.out.println("Exception is fired in redirector getter. error:" + e.getMessage()); e.printStackTrace(); } System.out.println("Real IP address is " + result); return result; }
From source file:eu.geopaparazzi.library.network.NetworkUtilities.java
/** * Sends an HTTP GET request to a url/*w w w. j a v a2s .co m*/ * * @param urlStr - The URL of the server. (Example: " http://www.yahoo.com/search") * @param file the output file. If it is a folder, it tries to get the file name from the header. * @param requestParameters - all the request parameters (Example: "param1=val1¶m2=val2"). * Note: This method will add the question mark (?) to the request - * DO NOT add it yourself * @param user * @param password * @return the file written. * @throws Exception */ public static File sendGetRequest4File(String urlStr, File file, String requestParameters, String user, String password) throws Exception { if (requestParameters != null && requestParameters.length() > 0) { urlStr += "?" + requestParameters; } HttpURLConnection conn = makeNewConnection(urlStr); conn.setRequestMethod("GET"); // conn.setDoOutput(true); conn.setDoInput(true); // conn.setChunkedStreamingMode(0); conn.setUseCaches(false); if (user != null && password != null) { conn.setRequestProperty("Authorization", getB64Auth(user, password)); } conn.connect(); if (file.isDirectory()) { // try to get the header String headerField = conn.getHeaderField("Content-Disposition"); String fileName = null; if (headerField != null) { String[] split = headerField.split(";"); for (String string : split) { String pattern = "filename="; if (string.toLowerCase().startsWith(pattern)) { fileName = string.replaceFirst(pattern, ""); break; } } } if (fileName == null) { // give a name fileName = "FILE_" + LibraryConstants.TIMESTAMPFORMATTER.format(new Date()); } file = new File(file, fileName); } InputStream in = null; FileOutputStream out = null; try { in = conn.getInputStream(); out = new FileOutputStream(file); byte[] buffer = new byte[(int) maxBufferSize]; int bytesRead = in.read(buffer, 0, (int) maxBufferSize); while (bytesRead > 0) { out.write(buffer, 0, bytesRead); bytesRead = in.read(buffer, 0, (int) maxBufferSize); } out.flush(); } finally { if (in != null) in.close(); if (out != null) out.close(); } return file; }
From source file:org.csware.ee.utils.Tools.java
public static String getSessionID(String path) { String[] sessionId = null;//from w w w .j a v a2s . c o m try { // URL URL url = new URL(path); // HttpURLConnection HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); String session_value = urlConn.getHeaderField("Set-Cookie"); sessionId = session_value.split(";"); // urlConn.setConnectTimeout(5 * 1000); // urlConn.connect(); } catch (Exception ex) { ex.printStackTrace(); } return sessionId[0]; }