List of usage examples for java.net HttpURLConnection getInputStream
public InputStream getInputStream() throws IOException
From source file:com.ecofactor.qa.automation.platform.util.FileUtil.java
/** * Download Mobile Zip File from jenkinsosx.ecofactor.com * @param webURL the web url//from w w w. j ava 2s . c o m * @param destinationPath the destination path */ public static void downloadFileFromURL(final String webURL, final String destinationPath) { LogUtil.setLogString(new StringBuilder("Download File from location :").append(webURL).toString(), true); try { final URL url = new URL(webURL); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); final InputStream inStream = connection.getInputStream(); final FileOutputStream outStream = new FileOutputStream(new File(destinationPath)); final byte[] buf = new byte[1024]; int inByte = inStream.read(buf); while (inByte >= 0) { outStream.write(buf, 0, inByte); inByte = inStream.read(buf); } outStream.flush(); outStream.close(); } catch (Exception e) { LOGGER.error("Error in download file", e); } }
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 {/*from ww w . ja va 2s .c om*/ 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:com.uniteddev.Unity.Downloader.java
public static void downloadFiles() throws MalformedURLException, IOException, InterruptedException { class downloadFile implements Runnable { private int i; downloadFile(int i) { this.i = i; }//ww w .java2 s .c o m public void run() { String filename = files.get(this.i).substring(files.get(this.i).lastIndexOf('/') + 1, files.get(this.i).length()); File f = new File(Minecraft.getWorkingDirectory(), files.get(this.i)); try { Login.progressText.setText("Downloading: " + filename); System.out.println("Downloading: " + filename); //System.out.println("Currently attempting Pool Index: "+this.i); HttpURLConnection connect_url = setupHTTP(Unity.url + Unity.folder + "/" + files.get(this.i)); FileUtils.copyInputStreamToFile(connect_url.getInputStream(), f); } catch (FileNotFoundException e) { Login.progressText.setText("File not found!"); } catch (MalformedURLException e) { System.out.println("DEV: FIX URL"); e.printStackTrace(); } catch (IOException e) { System.out.println("FileSystem Error"); e.printStackTrace(); } } } Login.progressText.setText("Downloading new files..."); System.out.println("Downloading new files..."); System.out.println("Number of files to download: " + files.size()); ExecutorService pool = Executors.newFixedThreadPool(10); for (int i = 0; i < files.size(); i++) { pool.submit(new downloadFile(i)); Login.progress.setValue((int) (((double) i / files.size()) * 100)); } pool.shutdown(); pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS); }
From source file:com.evrythng.java.wrapper.util.FileUtils.java
private static void validateConnectionAfterUpload(final HttpURLConnection connection) throws IOException { int responseCode = connection.getResponseCode(); if (responseCode == 200) { try (final InputStream is = connection.getInputStream()) { while (is.read() > 0) { // consume }/*ww w. j av a2 s . c o m*/ } } else { try (final InputStream is = connection.getErrorStream()) { final String error = IOUtils.toString(is); throw new IOException(String.format("Unable to upload file. Got error %d %s: %s", responseCode, connection.getResponseMessage(), error)); } } connection.disconnect(); }
From source file:Main.java
public static void server2mobile(Context context, String type) { String serverPath = "http://shaunrain.zicp.net/FileUp/QueryServlet?type=" + type; try {/*from ww w .j a v a2s .c om*/ URL url = new URL(serverPath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(10000); conn.setRequestMethod("GET"); int code = conn.getResponseCode(); Log.d("code", code + ""); if (code == 200) { InputStream is = conn.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int len = 0; byte[] buffer = new byte[1024]; while ((len = is.read(buffer)) != -1) { baos.write(buffer, 0, len); } is.close(); conn.disconnect(); String result = new String(baos.toByteArray()); String[] results = result.split("[$]"); for (String r : results) { if (r.length() != 0) { URL json = new URL(r); HttpURLConnection con = (HttpURLConnection) json.openConnection(); con.setConnectTimeout(5000); con.setRequestMethod("GET"); int co = con.getResponseCode(); if (co == 200) { File jsonFile; if (r.endsWith("clear.json")) { jsonFile = new File( Environment.getExternalStorageDirectory() + "/traffic_json/clear.json"); } else if (r.endsWith("crowd.json")) { jsonFile = new File( Environment.getExternalStorageDirectory() + "/traffic_json/crowd.json"); } else if (r.endsWith("trouble.json")) { jsonFile = new File( Environment.getExternalStorageDirectory() + "/traffic_json/trouble.json"); } else { jsonFile = new File( Environment.getExternalStorageDirectory() + "/traffic_json/control.json"); } if (jsonFile.exists()) jsonFile.delete(); jsonFile.createNewFile(); try (BufferedReader reader = new BufferedReader( new InputStreamReader(con.getInputStream(), "gb2312")); BufferedWriter writer = new BufferedWriter(new FileWriter(jsonFile));) { String line = null; while ((line = reader.readLine()) != null) { writer.write(line); } } } con.disconnect(); } } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:net.ftb.data.news.RSSReader.java
public static List<NewsArticle> readRSS() { try {//from www. j a v a 2 s . com List<NewsArticle> news = Lists.newArrayList(); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); URL u = new URL(Locations.feedURL); HttpURLConnection conn = (HttpURLConnection) u.openConnection(); conn.connect(); if (conn.getResponseCode() != 200) { Logger.logWarn("News download failed"); AppUtils.debugConnection(conn); conn.disconnect(); return null; } Document doc = builder.parse(conn.getInputStream()); NodeList nodes = doc.getElementsByTagName("item"); for (int i = 0; i < nodes.getLength(); i++) { Element element = (Element) nodes.item(i); NewsArticle article = new NewsArticle(); article.setTitle(getTextValue(element, "title")); article.setHyperlink(getTextValue(element, "link")); article.setBody(getTextValue(element, "content:encoded")); article.setDate(getTextValue(element, "pubDate")); news.add(article); } return news; } catch (Exception ex) { Logger.logWarn("News download failed", ex); return null; } }
From source file:com.wisdombud.right.client.common.HttpKit.java
private static String readResponseString(HttpURLConnection conn) { final StringBuilder sb = new StringBuilder(); InputStream inputStream = null; try {/*from w w w .j a v a 2s.c om*/ inputStream = conn.getInputStream(); final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, CHARSET)); String line = null; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } return sb.toString(); } catch (final Exception e) { throw new RuntimeException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (final IOException e) { } } } }
From source file:Main.java
public static Bitmap downLoadBitmap(String httpUrl) { InputStream inputStream = null; try {//w w w . ja v a 2s. com URL url = new URL(httpUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.setReadTimeout(5000); conn.setConnectTimeout(5000); conn.connect(); int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { inputStream = conn.getInputStream(); Bitmap bitmap = BitmapFactory.decodeStream(inputStream); return bitmap; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; }
From source file:com.camel.trainreserve.JDKHttpsClient.java
protected static String getResponseAsString(HttpURLConnection conn) throws IOException { String charset = getResponseCharset(conn.getContentType()); InputStream es = conn.getErrorStream(); if (es == null) { return getStreamAsString(conn.getInputStream(), charset); } else {//from w w w .j a v a2 s . c om String msg = getStreamAsString(es, charset); if (StringUtils.isEmpty(msg)) { throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage()); } else { throw new IOException(msg); } } }
From source file:de.Keyle.MyPet.util.player.UUIDFetcher.java
public static Map<String, UUID> call(List<String> names) { names = new ArrayList<String>(names); Iterator<String> iterator = names.iterator(); while (iterator.hasNext()) { String playerName = iterator.next(); if (fetchedUUIDs.containsKey(playerName)) { iterator.remove();/*from w ww. j a v a 2 s.c om*/ } } if (names.size() == 0) { return readonlyFetchedUUIDs; } int count = names.size(); DebugLogger.info("get UUIDs for " + names.size() + " player(s)"); int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST); try { for (int i = 0; i < requests; i++) { HttpURLConnection connection = createConnection(); String body = JSONArray.toJSONString(names.subList(i * 100, Math.min((i + 1) * 100, names.size()))); writeBody(connection, body); JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream())); count -= array.size(); for (Object profile : array) { JSONObject jsonProfile = (JSONObject) profile; String id = (String) jsonProfile.get("id"); String name = (String) jsonProfile.get("name"); UUID uuid = UUIDFetcher.getUUID(id); fetchedUUIDs.put(name, uuid); } if (rateLimiting && i != requests - 1) { Thread.sleep(100L); } } } catch (InterruptedException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } if (count > 0) { MyPetLogger.write("Can not get UUIDs for " + count + " players. Pets of these player may be lost."); } return readonlyFetchedUUIDs; }