List of usage examples for java.net HttpURLConnection getResponseCode
public int getResponseCode() throws IOException
From source file:brainleg.app.util.AppWeb.java
public static String post(String url, NameValuePair[] postParameters) throws RequestRejectedException, IOException { HttpConfigurable.getInstance().prepareURL(getUrl("api/proxyTest")); HttpURLConnection connection = doPost(url, join(Arrays.asList(postParameters))); int responseCode = connection.getResponseCode(); String responseText;/*from w ww . j a v a 2 s . c o m*/ InputStream is = new BufferedInputStream(connection.getInputStream()); try { responseText = readFrom(is); } finally { is.close(); } if (responseCode != HttpURLConnection.HTTP_OK) { // if this is 400 this is an application error (something is rejected by the app) if (responseCode == 400 && responseText != null) { //normally we return error messages like this: REQUIRED_PARAM_MISSING:Required parameters missing List<String> tokens = Lists .newArrayList(Splitter.on(":").omitEmptyStrings().trimResults().split(responseText)); if (tokens.isEmpty()) { throw new RequestRejectedException(); } else if (tokens.size() == 1) { throw new RequestRejectedException(tokens.get(0), null); } else { throw new RequestRejectedException(tokens.get(0), tokens.get(1)); } } else { throw new IOException("response code from server: " + responseCode); } } else { return responseText; } }
From source file:Main.java
public static URI unredirect(URI uri) throws IOException { if (!REDIRECTOR_DOMAINS.contains(uri.getHost())) { return uri; }//w ww . j av a 2 s .co m URL url = uri.toURL(); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setDoInput(false); connection.setRequestMethod("HEAD"); connection.setRequestProperty("User-Agent", "ZXing (Android)"); try { connection.connect(); switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_MULT_CHOICE: case HttpURLConnection.HTTP_MOVED_PERM: case HttpURLConnection.HTTP_MOVED_TEMP: case HttpURLConnection.HTTP_SEE_OTHER: case 307: // No constant for 307 Temporary Redirect ? String location = connection.getHeaderField("Location"); if (location != null) { try { return new URI(location); } catch (URISyntaxException e) { // nevermind } } } return uri; } finally { connection.disconnect(); } }
From source file:Main.java
public static boolean hasActiveInternetConnection(Context context) { if (isNetworkAvailable(context)) { try {/*w w w.j av a 2 s .c o m*/ HttpURLConnection connection = (HttpURLConnection) (new URL( "http://clients3.google.com/generate_204")).openConnection(); connection.setRequestProperty("User-Agent", "Test"); connection.setRequestProperty("Connection", "close"); connection.setReadTimeout(1500); connection.connect(); return (connection.getResponseCode() == 204 && connection.getContentLength() == 0); } catch (IOException e) { Log.e("ERROR", "Error checking internet connection"); } } else Log.e("ERROR", "No network available"); return false; }
From source file:edu.jhu.cvrg.timeseriesstore.opentsdb.TimeSeriesUtility.java
protected static String readHttpResponse(HttpURLConnection httpConnection) throws OpenTSDBException, IOException { String result = ""; int responseCode = httpConnection.getResponseCode(); if (responseCode == 200) { result = readHTTPConnection(httpConnection); } else if (responseCode == 204) { result = String.valueOf(responseCode); } else {// ww w. java2 s. com throw new OpenTSDBException(responseCode, httpConnection.getURL().toString(), ""); } httpConnection.disconnect(); return result; }
From source file:io.cloudex.cloud.impl.google.compute.GoogleMetaData.java
/** * Call the metadata server, this returns details for the current instance not for * different instances. In order to retrieve the meta data of different instances * we just use the compute api, see getInstance * @param path/*from w w w .ja va 2 s .co m*/ * @return * @throws IOException */ public static String getMetaData(String path) throws IOException { log.debug("Retrieving metadata from server, path: " + path); URL metadata = new URL(METADATA_SERVER_URL + path); HttpURLConnection con = (HttpURLConnection) metadata.openConnection(); // optional default is GET //con.setRequestMethod("GET"); //add request header con.setRequestProperty("Metadata-Flavor", "Google"); int responseCode = con.getResponseCode(); StringBuilder response = new StringBuilder(); if (responseCode == 200) { try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) { String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } } } else { String msg = "Metadata server responded with status code: " + responseCode; log.error(msg); throw new IOException(msg); } log.debug("Successfully retrieved metadata from server"); return response.toString(); }
From source file:com.meetingninja.csse.database.GroupDatabaseAdapter.java
public static Group getGroup(String groupID) throws IOException { // Server URL setup String _url = getBaseUri().appendPath(groupID).build().toString(); // Establish connection URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // add request header conn.setRequestMethod("GET"); addRequestHeader(conn, false);/* w ww . jav a 2 s.co m*/ // Get server response int responseCode = conn.getResponseCode(); String response = getServerResponse(conn); JsonNode groupNode = MAPPER.readTree(response); return parseGroup(groupNode, new Group()); }
From source file:com.meetingninja.csse.database.NotesDatabaseAdapter.java
public static Boolean deleteNote(String noteID) throws IOException { String _url = getBaseUri().appendPath(noteID).build().toString(); URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // add request header conn.setRequestMethod(IRequest.DELETE); addRequestHeader(conn, false);//ww w.ja v a 2 s .c o m int responseCode = conn.getResponseCode(); String response = getServerResponse(conn); boolean result = false; JsonNode tree = MAPPER.readTree(response); if (!response.isEmpty()) { if (!tree.has(Keys.DELETED)) { result = true; } else { logError("note.del.err", tree); } } conn.disconnect(); return result; }
From source file:jfix.util.Urls.java
/** * Returns true if given url can be connected via HTTP within given timeout * (specified in seconds). Otherwise the url might be broken. *//*from w ww .j av a 2 s . c o m*/ public static boolean isConnectable(String url, int timeout) { try { URLConnection connection = new URL(url).openConnection(); if (connection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setConnectTimeout(timeout * 1000); httpConnection.setReadTimeout(timeout * 1000); httpConnection.connect(); int response = httpConnection.getResponseCode(); httpConnection.disconnect(); return response == HttpURLConnection.HTTP_OK; } } catch (Exception e) { return false; } return false; }
From source file:jfix.util.Urls.java
/** * Returns the status code for connecting given url with given timeout. * Returns 0 if an IOException occurs./*ww w . java 2 s . c o m*/ */ public static int getStatus(String url, int timeout) { try { URLConnection connection = new URL(url).openConnection(); if (connection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setConnectTimeout(timeout * 1000); httpConnection.setReadTimeout(timeout * 1000); httpConnection.connect(); int response = httpConnection.getResponseCode(); httpConnection.disconnect(); return response; } } catch (IOException e) { // pass } return 0; }
From source file:com.alexoree.jenkins.Main.java
private static String download(String localName, String remoteUrl) throws Exception { URL obj = new URL(remoteUrl); HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); conn.setReadTimeout(5000);//from w w w. j a v a 2s . c o m System.out.println("Request URL ... " + remoteUrl); boolean redirect = false; // normally, 3xx is redirect int status = conn.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; } if (redirect) { // get redirect url from "location" header field String newUrl = conn.getHeaderField("Location"); // get the cookie if need, for login String cookies = conn.getHeaderField("Set-Cookie"); // open the new connnection again conn = (HttpURLConnection) new URL(newUrl).openConnection(); String version = newUrl.substring(newUrl.lastIndexOf("/", newUrl.lastIndexOf("/") - 1) + 1, newUrl.lastIndexOf("/")); String pluginname = localName.substring(localName.lastIndexOf("/") + 1); String ext = ""; if (pluginname.endsWith(".war")) ext = ".war"; else ext = ".hpi"; pluginname = pluginname.replace(ext, ""); localName = localName.replace(pluginname + ext, "/download/plugins/" + pluginname + "/" + version + "/"); new File(localName).mkdirs(); localName += pluginname + ext; System.out.println("Redirect to URL : " + newUrl); } if (new File(localName).exists()) { System.out.println(localName + " exists, skipping"); return localName; } byte[] buffer = new byte[2048]; FileOutputStream baos = new FileOutputStream(localName); InputStream inputStream = conn.getInputStream(); int totalBytes = 0; int read = inputStream.read(buffer); while (read > 0) { totalBytes += read; baos.write(buffer, 0, read); read = inputStream.read(buffer); } System.out.println("Retrieved " + totalBytes + "bytes"); return localName; }