List of usage examples for java.net HttpURLConnection getResponseCode
public int getResponseCode() throws IOException
From source file:io.webfolder.cdp.ChromiumDownloader.java
public static ChromiumVersion getLatestVersion() { String url = DOWNLOAD_HOST;//from ww w. j a v a2 s.co m if (WINDOWS) { url += "/Win_x64/LAST_CHANGE"; } else if (LINUX) { url += "/Linux_x64/LAST_CHANGE"; } else if (MAC) { url += "/Mac/LAST_CHANGE"; } else { throw new CdpException("Unsupported OS found - " + OS); } try { URL u = new URL(url); HttpURLConnection conn = (HttpURLConnection) u.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); if (conn.getResponseCode() != 200) { throw new CdpException(conn.getResponseCode() + " - " + conn.getResponseMessage()); } String result = null; try (Scanner s = new Scanner(conn.getInputStream())) { s.useDelimiter("\\A"); result = s.hasNext() ? s.next() : ""; } return new ChromiumVersion(Integer.parseInt(result)); } catch (IOException e) { throw new CdpException(e); } }
From source file:dk.nsi.minlog.test.utils.TestHelper.java
public static String sendRequest(String url, String action, String docXml, boolean failOnError) throws IOException, ServiceException { URL u = new URL(url); HttpURLConnection uc = (HttpURLConnection) u.openConnection(); uc.setDoOutput(true);/*from ww w. j a va 2 s .com*/ uc.setDoInput(true); uc.setRequestMethod("POST"); uc.setRequestProperty("SOAPAction", "\"" + action + "\""); uc.setRequestProperty("Content-Type", "text/xml; charset=utf-8;"); OutputStream os = uc.getOutputStream(); IOUtils.write(docXml, os, "UTF-8"); os.flush(); os.close(); InputStream is; if (uc.getResponseCode() != 200) { is = uc.getErrorStream(); } else { is = uc.getInputStream(); } String res = IOUtils.toString(is); is.close(); if (uc.getResponseCode() != 200 && (uc.getResponseCode() != 500 || failOnError)) { throw new ServiceException(res); } uc.disconnect(); return res; }
From source file:com.jeffrodriguez.webtools.client.URLConnectionWebClientImpl.java
private static void checkForErrors(HttpURLConnection connection) throws IOException { // If this is a 200-range response code, just return if (connection.getResponseCode() >= 200 && connection.getResponseCode() < 300) { return;//from w ww .jav a 2 s .co m } // Build the IO Exception IOException e = new IOException(connection.getResponseCode() + ": " + connection.getResponseMessage()); // Get the response as a string String response = IOUtils.toString(connection.getErrorStream(), "ISO-8859-1"); // Log it logger.log(Level.SEVERE, response, e); // Throw it throw e; }
From source file:com.facebook.fresco.sample.urlsfetcher.ImageUrlsFetcher.java
@Nullable private static String downloadContentAsString(String urlString) throws IOException { InputStream is = null;//from w w w . j a va2s.c om try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", IMGUR_CLIENT_ID); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query conn.connect(); int response = conn.getResponseCode(); if (response != HttpStatus.SC_OK) { FLog.e(TAG, "Album request returned %s", response); return null; } is = conn.getInputStream(); return readAsString(is); } finally { if (is != null) { is.close(); } } }
From source file:net.maxgigapop.mrs.driver.openstack.OpenStackRESTClient.java
private static String sendGET(URL url, HttpURLConnection con, String userAgent, String tokenId) throws IOException { con.setRequestMethod("GET"); con.setRequestProperty("User-Agent", userAgent); con.setRequestProperty("X-Auth-Token", tokenId); logger.log(Level.INFO, "Sending GET request to URL : {0}", url); int responseCode = con.getResponseCode(); logger.log(Level.INFO, "Response Code : {0}", responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine;//from w ww . j a va 2 s .c o m StringBuilder responseStr = new StringBuilder(); while ((inputLine = in.readLine()) != null) { responseStr.append(inputLine); } in.close(); return responseStr.toString(); }
From source file:com.cyphermessenger.client.SyncRequest.java
public static CypherUser registerUser(String username, String password, String captchaValue, Captcha captcha) throws IOException, APIErrorException { if (!captcha.verify(captchaValue)) { throw new APIErrorException(StatusCode.CAPTCHA_INVALID); }/*from ww w . j a va 2 s .c om*/ username = username.toLowerCase(); captchaValue = captchaValue.toLowerCase(); byte[] serverPassword = Utils.cryptPassword(password.getBytes(), username); byte[] localPassword = Utils.sha256(password); String serverPasswordEncoded = Utils.BASE64_URL.encode(serverPassword); ECKey key = new ECKey(); byte[] publicKey = key.getPublicKey(); byte[] privateKey = key.getPrivateKey(); try { privateKey = Encrypt.process(localPassword, privateKey); } catch (InvalidCipherTextException ex) { throw new RuntimeException(ex); } String[] keys = new String[] { "captchaToken", "captchaValue", "username", "password", "publicKey", "privateKey" }; String[] vals = new String[] { captcha.captchaToken, captchaValue, username, serverPasswordEncoded, Utils.BASE64_URL.encode(publicKey), Utils.BASE64_URL.encode(privateKey) }; HttpURLConnection conn = doRequest("register", null, keys, vals); if (conn.getResponseCode() != 200) { throw new IOException("Server error"); } InputStream in = conn.getInputStream(); JsonNode node = MAPPER.readTree(in); conn.disconnect(); int statusCode = node.get("status").asInt(); if (statusCode == StatusCode.OK) { long userID = node.get("userID").asLong(); long keyTime = node.get("timestamp").asLong(); key.setTime(keyTime); return new CypherUser(username, localPassword, serverPassword, userID, key, keyTime); } else { throw new APIErrorException(statusCode); } }
From source file:com.choices.imagecompare.urlsfetcher.ImageUrlsFetcher.java
@Nullable private static String downloadContentAsString(String urlString) throws IOException { InputStream is = null;//from w w w . j a va 2s .c om try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", IMGUR_CLIENT_ID); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query conn.connect(); int response = conn.getResponseCode(); if (response != SC_OK) { FLog.e(TAG, "Album request returned %s", response); return null; } is = conn.getInputStream(); return readAsString(is); } finally { if (is != null) { is.close(); } } }
From source file:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java
/** * Check if specified dataset already exists on server * /* w ww . j ava2s . c om*/ * @param dataSetName * @return boolean true if the dataset already exits, false if not * @throws IOException * @throws HttpException */ public static boolean chechIfExist(String dataSetName) throws IOException, HttpException { boolean exists = false; URL url = new URL(HOST + "/$/datasets/" + dataSetName); final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.setUseCaches(false); httpConnection.setRequestMethod("GET"); // handle HTTP/HTTPS strange behaviour httpConnection.connect(); httpConnection.disconnect(); // handle response switch (httpConnection.getResponseCode()) { case HttpURLConnection.HTTP_OK: exists = true; break; case HttpURLConnection.HTTP_NOT_FOUND: break; default: throw new HttpException( httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage()); } return exists; }
From source file:org.openbmap.soapclient.CheckServerTask.java
/** * Checks connection to openbmap.org//from w w w . j a v a 2 s . c om * @return true on successful http connection */ private static boolean isOnline() { try { Log.v(TAG, "Ping " + Preferences.VERSION_CHECK_URL); final URL url = new URL(Preferences.VERSION_CHECK_URL); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Connection", "close"); connection.setConnectTimeout(CONNECTION_TIMEOUT); connection.connect(); if (connection.getResponseCode() == 200) { Log.i(TAG, String.format("Good: Server reply %s - device & server online", connection.getResponseCode())); return true; } else { Log.w(TAG, String.format("Bad: Http ping failed (server reply %s).", connection.getResponseCode())); } } catch (final IOException e) { Log.w(TAG, "Bad: Http ping failed (no response).."); } return false; }
From source file:Main.java
public static String callJsonAPI(String urlString) { // Use HttpURLConnection as per Android 6.0 spec, instead of less efficient HttpClient HttpURLConnection urlConnection = null; StringBuilder jsonResult = new StringBuilder(); try {/*w ww . j a v a2 s.c om*/ URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setUseCaches(false); urlConnection.setConnectTimeout(TIMEOUT_CONNECTION); urlConnection.setReadTimeout(TIMEOUT_READ); urlConnection.connect(); int status = urlConnection.getResponseCode(); switch (status) { case 200: case 201: BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line; while ((line = br.readLine()) != null) { jsonResult.append(line).append("\n"); } br.close(); } } catch (MalformedURLException e) { System.err.print(e.getMessage()); return e.getMessage(); } catch (IOException e) { System.err.print(e.getMessage()); return e.getMessage(); } finally { if (urlConnection != null) { try { urlConnection.disconnect(); } catch (Exception e) { System.err.print(e.getMessage()); } } } return jsonResult.toString(); }