List of usage examples for java.net HttpURLConnection getResponseCode
public int getResponseCode() throws IOException
From source file:com.uksf.mf.core.utility.ClassNames.java
/** * Checks if connection to URL can be established * @param url url to check//w w w . jav a 2 s . c o m * @return connection state * @throws IOException error */ private static boolean checkConnection(URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(1500); connection.setReadTimeout(1500); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)"); connection.connect(); return connection.getResponseCode() == 404; }
From source file:Main.java
/** * Given a string url, connects and returns response code * * @param urlString string to fetch * @param readTimeOutMs read time out * @param connectionTimeOutMs connection time out * @param urlRedirect should use urlRedirect * @param useCaches should use cache * @return httpResponseCode http response code * @throws IOException/*w w w . j ava2 s . c o m*/ */ public static int checkUrlWithOptions(String urlString, int readTimeOutMs, int connectionTimeOutMs, boolean urlRedirect, boolean useCaches) throws IOException { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(readTimeOutMs /* milliseconds */); connection.setConnectTimeout(connectionTimeOutMs /* milliseconds */); connection.setRequestMethod("GET"); connection.setInstanceFollowRedirects(urlRedirect); connection.setUseCaches(useCaches); // Starts the query connection.connect(); int responseCode = connection.getResponseCode(); connection.disconnect(); return responseCode; }
From source file:io.github.retz.web.JobRequestRouter.java
public static boolean statHTTPFile(String url, String name) { String addr = url.replace("files/browse", "files/download") + "%2F" + maybeURLEncode(name); HttpURLConnection conn = null; try {/* ww w. j ava 2s.c o m*/ conn = (HttpURLConnection) new URL(addr).openConnection(); conn.setRequestMethod("HEAD"); conn.setDoOutput(false); LOG.debug(conn.getResponseMessage()); return conn.getResponseCode() == 200 || conn.getResponseCode() == 204; } catch (IOException e) { LOG.debug("Failed to fetch {}: {}", addr, e.toString()); return false; } finally { if (conn != null) { conn.disconnect(); } } }
From source file:net.amigocraft.mpt.util.MiscUtil.java
public static JSONObject getRemoteIndex(String path) throws MPTException { try {//w w w .j a v a2s . c om URL url = new URL(path + (!path.endsWith("/") ? "/" : "") + "mpt.json"); // get URL object for data file URLConnection conn = url.openConnection(); if (conn instanceof HttpURLConnection) { HttpURLConnection http = (HttpURLConnection) conn; // cast the connection int response = http.getResponseCode(); // get the response if (response >= 200 && response <= 299) { // verify the remote isn't upset at us InputStream is = http.getInputStream(); // open a stream to the URL BufferedReader reader = new BufferedReader(new InputStreamReader(is)); // get a reader JSONParser parser = new JSONParser(); // get a new parser String line; StringBuilder content = new StringBuilder(); while ((line = reader.readLine()) != null) content.append(line); JSONObject json = (JSONObject) parser.parse(content.toString()); // parse JSON object // vefify remote config is valid if (json.containsKey("packages") && json.get("packages") instanceof JSONObject) { return json; } else throw new MPTException( ERROR_COLOR + "Index for repository at " + path + "is missing required elements!"); } else { String error = ERROR_COLOR + "Remote returned bad response code! (" + response + ")"; if (!http.getResponseMessage().isEmpty()) error += " The remote says: " + ChatColor.GRAY + ChatColor.ITALIC + http.getResponseMessage(); throw new MPTException(error); } } else throw new MPTException(ERROR_COLOR + "Bad protocol for URL!"); } catch (MalformedURLException ex) { throw new MPTException(ERROR_COLOR + "Cannot parse URL!"); } catch (IOException ex) { throw new MPTException(ERROR_COLOR + "Cannot open connection to URL!"); } catch (ParseException ex) { throw new MPTException(ERROR_COLOR + "Repository index is not valid JSON!"); } }
From source file:com.netflix.raigad.utils.SystemUtils.java
public static String getDataFromUrl(String url) { try {//from w w w. j a v a2 s . c om HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setConnectTimeout(1000); conn.setReadTimeout(1000); conn.setRequestMethod("GET"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Unable to get data for URL " + url); } byte[] b = new byte[2048]; ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataInputStream d = new DataInputStream((FilterInputStream) conn.getContent()); int c = 0; while ((c = d.read(b, 0, b.length)) != -1) bos.write(b, 0, c); String return_ = new String(bos.toByteArray(), Charsets.UTF_8); logger.info("Calling URL API: {} returns: {}", url, return_); conn.disconnect(); return return_; } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:net.line2soft.preambul.utils.Network.java
/** * Checks if a connection is possible between device and server. * @param address The URL to request/*from w w w . j a va 2s. c o m*/ * @return True if the connection is possible, false else */ public static boolean checkConnection(URL address) { boolean result = false; try { HttpURLConnection urlc = (HttpURLConnection) address.openConnection(); //urlc.setRequestProperty("User-Agent", "Android Application:"+Z.APP_VERSION); urlc.setRequestProperty("Connection", "close"); urlc.setConnectTimeout(1000); urlc.connect(); if (urlc.getResponseCode() == 200) { result = true; } } catch (Exception e) { ; } return result; }
From source file:com.blogspot.ryanfx.auth.GoogleUtil.java
/** * Sends the auth token to google and gets the json result. * @param token auth token//ww w . ja v a 2 s. c om * @return json result if valid request, null if invalid. * @throws IOException * @throws LoginException */ private static String issueTokenGetRequest(String token) throws IOException, LoginException { int timeout = 2000; URL u = new URL("https://www.googleapis.com/oauth2/v2/userinfo"); HttpURLConnection c = (HttpURLConnection) u.openConnection(); c.setRequestMethod("GET"); c.setRequestProperty("Content-length", "0"); c.setRequestProperty("Authorization", "OAuth " + token); c.setUseCaches(false); c.setAllowUserInteraction(false); c.setConnectTimeout(timeout); c.setReadTimeout(timeout); c.connect(); int status = c.getResponseCode(); if (status == HttpServletResponse.SC_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); return sb.toString(); } else if (status == HttpServletResponse.SC_UNAUTHORIZED) { Logger.getLogger(GoogleUtil.class.getName()).severe("Invalid token request: " + token); } return null; }
From source file:com.facebook.GraphResponse.java
@SuppressWarnings("resource") static List<GraphResponse> fromHttpConnection(HttpURLConnection connection, GraphRequestBatch requests) { InputStream stream = null;//from w w w . java 2s . c o m try { if (connection.getResponseCode() >= 400) { stream = connection.getErrorStream(); } else { stream = connection.getInputStream(); } return createResponsesFromStream(stream, connection, requests); } catch (FacebookException facebookException) { Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response <Error>: %s", facebookException); return constructErrorResponses(requests, connection, facebookException); } catch (JSONException exception) { Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response <Error>: %s", exception); return constructErrorResponses(requests, connection, new FacebookException(exception)); } catch (IOException exception) { Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response <Error>: %s", exception); return constructErrorResponses(requests, connection, new FacebookException(exception)); } catch (SecurityException exception) { Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response <Error>: %s", exception); return constructErrorResponses(requests, connection, new FacebookException(exception)); } finally { Utility.closeQuietly(stream); } }
From source file:Main.java
public static JSONObject updateRequest(String query) { HttpURLConnection connection = null; try {/*w ww . j a v a2 s .co m*/ connection = (HttpURLConnection) new URL(url + query).openConnection(); connection.setRequestMethod("PUT"); connection.setRequestProperty("Accept-Charset", charset); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write("Resource content"); out.close(); statusCode = connection.getResponseCode(); if (statusCode != 200) { return null; } InputStream response = connection.getInputStream(); BufferedReader bR = new BufferedReader(new InputStreamReader(response)); String line = ""; StringBuilder responseStrBuilder = new StringBuilder(); while ((line = bR.readLine()) != null) { responseStrBuilder.append(line); } response.close(); return new JSONObject(responseStrBuilder.toString()); } catch (IOException | JSONException e) { e.printStackTrace(); } return new JSONObject(); }
From source file:com.meetingninja.csse.database.TaskDatabaseAdapter.java
public static void getTask(Task t) throws JsonParseException, JsonMappingException, IOException { // Server URL setup String _url = getBaseUri().appendPath(t.getID()).build().toString(); URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // add request header conn.setRequestMethod(IRequest.GET); addRequestHeader(conn, false);/*from w w w .j a v a2s .c o m*/ // Get server response int responseCode = conn.getResponseCode(); String response = getServerResponse(conn); // Initialize ObjectMapper // List<Task> taskList = new ArrayList<Task>(); final JsonNode taskNode = MAPPER.readTree(response); // if(taskArray.isArray()){ // for(final JsonNode taskNode : taskArray){ parseTask(taskNode, t); // if(t!=null){ // taskList.add(t); // } // } // } conn.disconnect(); // return void; }