List of usage examples for java.net HttpURLConnection getResponseCode
public int getResponseCode() throws IOException
From source file:com.meetingninja.csse.database.ContactDatabaseAdapter.java
public static List<Contact> deleteContact(String relationID) throws IOException { String _url = getBaseUri().appendPath("Relations").appendPath(relationID).build().toString(); URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(IRequest.DELETE); addRequestHeader(conn, false);/*from w ww . jav a 2 s . c om*/ 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(TAG, tree); } } conn.disconnect(); SessionManager session = SessionManager.getInstance(); List<Contact> contacts = getContacts(session.getUserID()); return contacts; }
From source file:Main.java
public static boolean isConnectionAvailable() { class NetworkCheckTask extends AsyncTask<Void, Void, Boolean> { @Override//ww w.ja va 2s . co m protected Boolean doInBackground(Void... params) { try { URL url = new URL(MAD_SERVER + "/sync.html"); HttpURLConnection conn = null; conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(999); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.connect(); if (conn.getResponseCode() == 200) return true; else return false; } catch (Exception e) { return false; } } } try { NetworkCheckTask async = new NetworkCheckTask(); async.execute(); return async.get(); } catch (Exception e) { return false; } }
From source file:eu.liveandgov.ar.utilities.OS_Utils.java
/** * Check if URL exists /*from w ww . j a v a 2 s . c o m*/ * * @param urlSTR * @return */ public static boolean exists(String URLName) { try { HttpURLConnection.setFollowRedirects(false); // note : you may also need // HttpURLConnection.setInstanceFollowRedirects(false) HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection(); con.setRequestMethod("HEAD"); return (con.getResponseCode() == HttpURLConnection.HTTP_OK); } catch (Exception e) { return false; } }
From source file:net.maxgigapop.mrs.driver.openstack.OpenStackRESTClient.java
private static String sendDELETE(URL url, HttpURLConnection con) throws IOException { logger.log(Level.INFO, "Sending DELETE 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;// w w w.jav a2 s . c o m StringBuilder responseStr = new StringBuilder(); while ((inputLine = in.readLine()) != null) { responseStr.append(inputLine); } in.close(); return responseStr.toString(); }
From source file:de.egore911.versioning.deployer.Main.java
private static void perform(String arg, CommandLine line) throws IOException { URL url;/* w w w . j a va2s .c o m*/ try { url = new URL(arg); } catch (MalformedURLException e) { LOG.error("Invalid URI: {}", e.getMessage(), e); System.exit(1); return; } HttpURLConnection connection; try { connection = (HttpURLConnection) url.openConnection(); int response = connection.getResponseCode(); if (response != HttpURLConnection.HTTP_OK) { LOG.error("Could not download {}", url); connection.disconnect(); System.exit(1); return; } } catch (ConnectException e) { LOG.error("Error during download from URI {}: {}", url, e.getMessage()); System.exit(1); return; } XmlHolder xmlHolder = XmlHolder.getInstance(); DocumentBuilder documentBuilder = xmlHolder.documentBuilder; XPath xPath = xmlHolder.xPath; try { XPathExpression serverNameXpath = xPath.compile("/server/name/text()"); XPathExpression serverTargetdirXpath = xPath.compile("/server/targetdir/text()"); XPathExpression serverDeploymentsDeploymentXpath = xPath.compile("/server/deployments/deployment"); Document doc = documentBuilder.parse(connection.getInputStream()); connection.disconnect(); String serverName = (String) serverNameXpath.evaluate(doc, XPathConstants.STRING); LOG.info("Deploying {}", serverName); boolean shouldPerformCopy = !line.hasOption('r'); PerformCopy performCopy = new PerformCopy(xPath); boolean shouldPerformExtraction = !line.hasOption('r'); PerformExtraction performExtraction = new PerformExtraction(xPath); boolean shouldPerformCheckout = !line.hasOption('r'); PerformCheckout performCheckout = new PerformCheckout(xPath); boolean shouldPerformReplacement = true; PerformReplacement performReplacement = new PerformReplacement(xPath); String targetdir = (String) serverTargetdirXpath.evaluate(doc, XPathConstants.STRING); FileUtils.forceMkdir(new File(targetdir)); NodeList serverDeploymentsDeploymentNodes = (NodeList) serverDeploymentsDeploymentXpath.evaluate(doc, XPathConstants.NODESET); int max = serverDeploymentsDeploymentNodes.getLength(); for (int i = 0; i < serverDeploymentsDeploymentNodes.getLength(); i++) { Node serverDeploymentsDeploymentNode = serverDeploymentsDeploymentNodes.item(i); // Copy if (shouldPerformCopy) { performCopy.perform(serverDeploymentsDeploymentNode); } // Extraction if (shouldPerformExtraction) { performExtraction.perform(serverDeploymentsDeploymentNode); } // Checkout if (shouldPerformCheckout) { performCheckout.perform(serverDeploymentsDeploymentNode); } // Replacement if (shouldPerformReplacement) { performReplacement.perform(serverDeploymentsDeploymentNode); } logPercent(i + 1, max); } // validate that "${versioning:" is not present Collection<File> files = FileUtils.listFiles(new File(targetdir), TrueFileFilter.TRUE, TrueFileFilter.INSTANCE); for (File file : files) { String content; try { content = FileUtils.readFileToString(file); } catch (IOException e) { continue; } if (content.contains("${versioning:")) { LOG.error("{} contains placeholders even after applying the replacements", file.getAbsolutePath()); } } LOG.info("Done deploying {}", serverName); } catch (SAXException | IOException | XPathExpressionException e) { LOG.error("Error performing deployment: {}", e.getMessage(), e); } }
From source file:com.android.dialer.omni.PlaceUtil.java
/** * Executes a GET request and return a JSON object * @param url The API URL/*from w w w. j a v a 2s .c o m*/ * @return the JSON object * @throws IOException * @throws JSONException */ public static JSONObject getJsonRequest(String url) throws IOException, JSONException { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); if (DEBUG) Log.d(TAG, "Getting JSON from: " + url); con.setDoOutput(true); int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); JSONObject json = new JSONObject(response.toString()); return json; }
From source file:javaphpmysql.JavaPHPMySQL.java
public static void sendGet() { //Creamos un objeto JSON JSONObject jsonObj = new JSONObject(); //Aadimos el nombre, apellidos y email del usuario jsonObj.put("nombre", nombre); jsonObj.put("apellidos", apellidos); jsonObj.put("email", email); //Creamos una lista para almacenar el JSON List l = new LinkedList(); l.addAll(Arrays.asList(jsonObj)); //Generamos el String JSON String jsonString = JSONValue.toJSONString(l); System.out.println("JSON GENERADO:"); System.out.println(jsonString); System.out.println(""); try {//w w w.j a va 2 s . co m //Codificar el json a URL jsonString = URLEncoder.encode(jsonString, "UTF-8"); //Generar la URL String url = SERVER_PATH + "listenGet.php?json=" + jsonString; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("GET"); //add request header con.setRequestProperty("User-Agent", USER_AGENT); int responseCode = con.getResponseCode(); System.out.println("\nSending 'GET' request to URL : " + url); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result System.out.println(response.toString()); } catch (Exception e) { e.printStackTrace(); } }
From source file:imageLines.ImageHelpers.java
/**Read a jpeg image from a url into a BufferedImage*/ public static BufferedImage readAsBufferedImage(URL imageURL) { InputStream i = null;//from w w w . jav a2 s . c o m try { URLConnection u = imageURL.openConnection(); u.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.151 Safari/535.19"); if (u instanceof HttpURLConnection) { HttpURLConnection h = (HttpURLConnection) u; if (h.getResponseCode() == 403) throw new Exception("403 forbidden"); } i = u.getInputStream(); BufferedImage bi = ImageIO.read(i); return bi; } catch (Exception e) { System.out.println(e + " for " + imageURL.toString() + "\n"); return null; } finally { try { i.close(); } catch (IOException ex) { } } }
From source file:de.egore911.versioning.deployer.performer.PerformExtraction.java
private static boolean extract(String uri, List<ExtractionPair> extractions) { URL url;/*w w w . j ava2 s.c o m*/ try { url = new URL(uri); } catch (MalformedURLException e) { LOG.error("Invalid URI: {}", e.getMessage(), e); return false; } try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); int response = connection.getResponseCode(); int lastSlash = uri.lastIndexOf('/'); if (lastSlash < 0) { LOG.error("Invalid URI: {}", uri); return false; } int lastDot = uri.lastIndexOf('.'); if (lastDot < 0) { LOG.error("Invalid URI: {}", uri); return false; } File downloadFile = File.createTempFile(uri.substring(lastSlash + 1), uri.substring(lastDot + 1)); downloadFile.deleteOnExit(); if (response == HttpURLConnection.HTTP_OK) { try (InputStream in = connection.getInputStream(); FileOutputStream out = new FileOutputStream(downloadFile)) { IOUtils.copy(in, out); } LOG.debug("Downloaded {} to {}", url, downloadFile.getAbsolutePath()); Set<ExtractionPair> usedExtractions = new HashSet<>(); // Perform extractions try (ZipFile zipFile = new ZipFile(downloadFile)) { Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); // Only extract files if (entry.isDirectory()) { continue; } for (ExtractionPair extraction : extractions) { String sourcePattern = extraction.source; if (FilenameUtils.wildcardMatch(entry.getName(), sourcePattern)) { usedExtractions.add(extraction); LOG.debug("Found matching file {} for source pattern {}", entry.getName(), sourcePattern); String filename = getSourcePatternMatch(entry.getName(), sourcePattern); // Workaround: If there is no matcher in 'sourcePattern' it will return the // complete path. Strip it down to the filename if (filename.equals(entry.getName())) { int lastIndexOf = filename.lastIndexOf('/'); if (lastIndexOf >= 0) { filename = filename.substring(lastIndexOf + 1); } } String name = UrlUtil.concatenateUrlWithSlashes(extraction.destination, filename); FileUtils.forceMkdir(new File(name).getParentFile()); try (InputStream in = zipFile.getInputStream(entry); FileOutputStream out = new FileOutputStream(name)) { IOUtils.copy(in, out); } LOG.debug("Extracted {} to {} from {}", entry.getName(), name, uri); } } } } for (ExtractionPair extraction : extractions) { if (!usedExtractions.contains(extraction)) { LOG.debug("Extraction {} to {} not used on {}", extraction.source, extraction.destination, uri); } } return true; } else { LOG.error("Could not download file: {}", uri); return false; } } catch (IOException e) { LOG.error("Could not download file: {}", e.getMessage(), e); return false; } }
From source file:com.microsoft.intellij.util.WAHelper.java
public static void sendGet(String sitePath) throws Exception { URL url = new URL(sitePath); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("User-Agent", "AzureToolkit for Intellij"); int responseCode = con.getResponseCode(); }