List of usage examples for java.net HttpURLConnection disconnect
public abstract void disconnect();
From source file:controllers.IndexServlet.java
private static void Track(HttpServletRequest request, HttpServletResponse response, PrintWriter writer) { String userAddress = request.getParameter("userAddress"); String fileName = request.getParameter("fileName"); String storagePath = DocumentManager.StoragePath(fileName, userAddress); String body = ""; try {//w w w . jav a 2s. com Scanner scanner = new Scanner(request.getInputStream()).useDelimiter("\\A"); body = scanner.hasNext() ? scanner.next() : ""; } catch (Exception ex) { writer.write("get request.getInputStream error:" + ex.getMessage()); return; } if (body.isEmpty()) { writer.write("empty request.getInputStream"); return; } JSONParser parser = new JSONParser(); JSONObject jsonObj; try { Object obj = parser.parse(body); jsonObj = (JSONObject) obj; } catch (Exception ex) { writer.write("JSONParser.parse error:" + ex.getMessage()); return; } long status = (long) jsonObj.get("status"); if (status == 2 || status == 3)//MustSave, Corrupted { String downloadUri = (String) jsonObj.get("url"); int saved = 1; try { URL url = new URL(downloadUri); java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection(); InputStream stream = connection.getInputStream(); if (stream == null) { throw new Exception("Stream is null"); } File savedFile = new File(storagePath); try (FileOutputStream out = new FileOutputStream(savedFile)) { int read; final byte[] bytes = new byte[1024]; while ((read = stream.read(bytes)) != -1) { out.write(bytes, 0, read); } out.flush(); } connection.disconnect(); } catch (Exception ex) { saved = 0; } } writer.write("{\"error\":0}"); }
From source file:edu.stanford.muse.launcher.Splash.java
private static boolean killRunningServer(String url) throws IOException { try {/*w w w .j a v a2 s . com*/ // attempt to fetch the page // throws a connect exception if the server is not even running // so catch it and return false String http = url + "/exit.jsp?message=Shutdown%20request%20from%20a%20different%20instance%20of%20ePADD"; // version num spaces and brackets screw up the URL connection err.println("Sending a kill request to " + http); HttpURLConnection u = (HttpURLConnection) new URL(http).openConnection(); u.connect(); if (u.getResponseCode() == 200) { u.disconnect(); return true; } u.disconnect(); } catch (ConnectException ce) { } return false; }
From source file:Main.java
/** * Make an HTTP request to the given URL and return a String as the response. *//*w w w . ja v a2 s . c o m*/ private static String makeHttpRequest(URL url) throws IOException { String jsonResponse = ""; // If the URL is null, then return early. if (url == null) { return jsonResponse; } HttpURLConnection urlConnection = null; InputStream inputStream = null; try { urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setReadTimeout(10000 /* milliseconds */); urlConnection.setConnectTimeout(15000 /* milliseconds */); urlConnection.setRequestMethod("GET"); urlConnection.connect(); /* If the request was successful (response code 200), then read the input stream and parse the response. */ if (urlConnection.getResponseCode() == 200) { inputStream = urlConnection.getInputStream(); jsonResponse = readFromStream(inputStream); } else { //handle exception } } catch (IOException e) { //handle exception } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (inputStream != null) { inputStream.close(); } } return jsonResponse; }
From source file:msearch.filmeSuchen.sender.MediathekSrf.java
public static boolean ping(String url) throws SRFException { url = url.replaceFirst("https", "http"); // Otherwise an exception may be thrown on invalid SSL certificates. try {/*w ww . j ava 2 s. c o m*/ HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setConnectTimeout(1000); //1000ms timeout for connect, read timeout to infinity connection.setReadTimeout(0); int responseCode = connection.getResponseCode(); connection.disconnect(); if (responseCode > 399 && responseCode != HttpURLConnection.HTTP_NOT_FOUND) { if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) { throw new SRFException("TEST"); } //MSLog.debugMeldung("SRF: " + responseCode + " + responseCode " + "Url " + url); return false; } return (200 <= responseCode && responseCode <= 399); } catch (IOException exception) { return false; } }
From source file:Main.java
public static byte[] retrieveImageData_fromUrl(String imageUrl) throws IOException { URL url = new URL(imageUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK"); // determine the image size and allocate a buffer int fileSize = connection.getContentLength(); byte[] imageData = new byte[fileSize]; // download the file Log.d(TAG, "fetching image " + imageUrl + " (" + fileSize + ")"); if (fileSize > 0) { BufferedInputStream istream = new BufferedInputStream(connection.getInputStream()); int bytesRead = 0; int offset = 0; while (bytesRead != -1 && offset < fileSize) { bytesRead = istream.read(imageData, offset, fileSize - offset); offset += bytesRead;//from w w w. j av a 2 s. com } istream.close(); } else Log.d(TAG, "fileSize is 0! skipping"); // clean up connection.disconnect(); return imageData; }
From source file:Main.java
private static String httpGet(String address) { InputStream inputStream = null; HttpURLConnection httpURLConnection = null; try {/*from ww w. ja va2 s. c o m*/ URL url = new URL(address); httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.connect(); if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { inputStream = httpURLConnection.getInputStream(); int len = 0; byte[] buffer = new byte[1024]; StringBuffer stringBuffer = new StringBuffer(); while ((len = inputStream.read(buffer)) != -1) { stringBuffer.append(new String(buffer, 0, len)); } return stringBuffer.toString(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { close(inputStream); if (httpURLConnection != null) { httpURLConnection.disconnect(); } } return null; }
From source file:Authentication.DinserverAuth.java
public static boolean Login(String nick, String pass, Socket socket) throws IOException { boolean logged = false; JSONObject authRequest = new JSONObject(); authRequest.put("username", nick); authRequest.put("auth_id", pass); String query = "http://127.0.0.1:5000/token"; URL url = new URL(query); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000);//from w w w . ja v a 2 s .co m conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); OutputStream os = conn.getOutputStream(); os.write(authRequest.toString().getBytes(Charset.forName("UTF-8"))); os.close(); String output = new String(); StringBuilder sb = new StringBuilder(); int HttpResult = conn.getResponseCode(); if (HttpResult == HttpURLConnection.HTTP_OK) { output = IOUtils.toString(new InputStreamReader(conn.getInputStream(), Charset.forName("UTF-8"))); } else { System.out.println(conn.getResponseMessage()); } JSONObject jsonObject = new JSONObject(output); logged = jsonObject.getBoolean("ok"); conn.disconnect(); if (logged) { if (DinserverMaster.addUser(nick, socket)) { System.out.println("User " + nick + " logged in"); } else { logged = false; } } return logged; }
From source file:edu.stanford.epadd.launcher.Splash.java
private static boolean isURLAlive(String url) throws IOException { try {/* w ww . j a va2 s . c o m*/ // attempt to fetch the page // throws a connect exception if the server is not even running // so catch it and return false // since "index" may auto load default archive, attach it to session, and redirect to "info" page, // we need to maintain the session across the pages. // see "Maintaining the session" at http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL)); out.println("Testing for already running ePADD by probing " + url); System.out.println("Testing for already running ePADD by probing " + url); HttpURLConnection u = (HttpURLConnection) new URL(url).openConnection(); if (u.getResponseCode() == 200) { u.disconnect(); out.println("ePADD is already running!"); return true; } u.disconnect(); } catch (ConnectException ce) { } out.println("Good, ePADD is not already running"); return false; }
From source file:com.surfs.storage.common.util.HttpUtils.java
public static String invokeHttpForGet(String path, String... agrs) throws IOException { URL url = new URL(path); LogFactory.info("rest url:" + url.toString()); HttpURLConnection con = null; try {/*ww w . j av a 2s . c o m*/ con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setConnectTimeout(10000); con.setReadTimeout(1000 * 60 * 30); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); for (String string : agrs) { con.setRequestProperty("Content-type", "application/json"); con.setRequestMethod("POST"); OutputStream out = con.getOutputStream(); out.write(string.getBytes("UTF-8")); } if (con.getResponseCode() != 200) throw new ConnectException(con.getResponseMessage()); InputStream is = con.getInputStream(); return readResponse(is); } catch (IOException e) { throw e; } finally { if (con != null) { con.disconnect(); } } }
From source file:core.Utility.java
private static ArrayList<String> getSynonymsWiktionary(String _word) throws MalformedURLException, IOException { ArrayList<String> _list = new ArrayList(); try {// w ww.j a va 2s.co m URL url = new URL("http://www.igrec.ca/project-files/wikparser/wikparser.php?word=" + _word + "&query=syn&lang=en"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; while ((output = br.readLine()) != null) { boolean isEmpty = output.contains("No listed synonyms.") || output.contains("ERROR: The Wiktionary API did not return a page for that word."); if (isEmpty) { conn.disconnect(); return _list; } else { String[] arr = output.trim().split(" "); for (String s : arr) { if (s.length() > 2) { _list.add(s); } } } } conn.disconnect(); } catch (MalformedURLException e) { throw e; } catch (IOException e) { throw e; } return _list; }