List of usage examples for java.net HttpURLConnection getInputStream
public InputStream getInputStream() throws IOException
From source file:com.magnet.plugin.common.helpers.URLHelper.java
public static InputStream loadUrl(final String url) throws Exception { final InputStream[] inputStreams = new InputStream[] { null }; final Exception[] exception = new Exception[] { null }; Future<?> downloadThreadFuture = ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { public void run() { try { HttpURLConnection connection; if (ApplicationManager.getApplication() != null) { connection = HttpConfigurable.getInstance().openHttpConnection(url); } else { connection = (HttpURLConnection) new URL(url).openConnection(); connection.setReadTimeout(CONNECTION_TIMEOUT); connection.setConnectTimeout(CONNECTION_TIMEOUT); }/*from w w w .j a va 2 s . c o m*/ connection.connect(); inputStreams[0] = connection.getInputStream(); } catch (IOException e) { exception[0] = e; } } }); try { downloadThreadFuture.get(5, TimeUnit.SECONDS); } catch (TimeoutException ignored) { } if (!downloadThreadFuture.isDone()) { downloadThreadFuture.cancel(true); throw new Exception(IdeBundle.message("updates.timeout.error")); } if (exception[0] != null) throw exception[0]; return inputStreams[0]; }
From source file:jfutbol.com.jfutbol.GcmSender.java
public static void SendNotification(int userId, int notificationCounter) { String msg[] = new String[2]; if (notificationCounter > 1) msg = new String[] { "Tienes " + notificationCounter + " nuevas notificaciones.", "/topics/" + userId }; else/*from w ww . j a v a 2 s . co m*/ msg = new String[] { "Tienes " + notificationCounter + " nueva notificacion.", "/topics/" + userId }; if (msg.length < 1 || msg.length > 2 || msg[0] == null) { System.err.println("usage: ./gradlew run -Pmsg=\"MESSAGE\" [-Pto=\"DEVICE_TOKEN\"]"); System.err.println(""); System.err.println( "Specify a test message to broadcast via GCM. If a device's GCM registration token is\n" + "specified, the message will only be sent to that device. Otherwise, the message \n" + "will be sent to all devices subscribed to the \"global\" topic."); System.err.println(""); System.err.println( "Example (Broadcast):\n" + "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\"\n" + "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\""); System.err.println(""); System.err.println("Example (Unicast):\n" + "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\"\n" + "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\""); System.exit(1); } try { // Prepare JSON containing the GCM message content. What to send and // where to send. JSONObject jGcmData = new JSONObject(); JSONObject jData = new JSONObject(); jData.put("message", msg[0].trim()); // Where to send GCM message. if (msg.length > 1 && msg[1] != null) { jGcmData.put("to", msg[1].trim()); } else { jGcmData.put("to", "/topics/global"); } // What to send in GCM message. jGcmData.put("data", jData); // Create connection to send GCM Message request. URL url = new URL("https://android.googleapis.com/gcm/send"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", "key=" + API_KEY); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestMethod("POST"); conn.setDoOutput(true); // Send GCM message content. OutputStream outputStream = conn.getOutputStream(); outputStream.write(jGcmData.toString().getBytes()); // Read GCM response. InputStream inputStream = conn.getInputStream(); String resp = IOUtils.toString(inputStream); updateNotificationAsSent(userId); System.out.println(resp); System.out.println("Check your device/emulator for notification or logcat for " + "confirmation of the receipt of the GCM message."); } catch (IOException e) { System.out.println("Unable to send GCM message."); System.out.println("Please ensure that API_KEY has been replaced by the server " + "API key, and that the device's registration token is correct (if specified)."); log.error(e.getMessage()); e.printStackTrace(); } }
From source file:com.facebook.fresco.sample.urlsfetcher.ImageUrlsFetcher.java
@Nullable private static String downloadContentAsString(String urlString) throws IOException { InputStream is = null;//from www.j av a2 s. com try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", IMGUR_CLIENT_ID); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query conn.connect(); int response = conn.getResponseCode(); if (response != HttpStatus.SC_OK) { FLog.e(TAG, "Album request returned %s", response); return null; } is = conn.getInputStream(); return readAsString(is); } finally { if (is != null) { is.close(); } } }
From source file:org.lightjason.agentspeak.action.buildin.rest.IBaseRest.java
/** * creates a HTTP connection and reads the data * * @param p_url url/*from w w w . j a v a 2 s . c o m*/ * @return url data * @throws IOException is thrown on connection errors */ private static String httpdata(final String p_url) throws IOException { final HttpURLConnection l_connection = (HttpURLConnection) new URL(p_url).openConnection(); // follow HTTP redirects l_connection.setInstanceFollowRedirects(true); // set a HTTP-User-Agent if not exists l_connection.setRequestProperty("User-Agent", (System.getProperty("http.agent") == null) || (System.getProperty("http.agent").isEmpty()) ? CCommon.PACKAGEROOT + CCommon.configuration().getString("version") : System.getProperty("http.agent")); // read stream data final InputStream l_stream = l_connection.getInputStream(); final String l_return = CharStreams.toString(new InputStreamReader(l_stream, (l_connection.getContentEncoding() == null) || (l_connection.getContentEncoding().isEmpty()) ? Charsets.UTF_8 : Charset.forName(l_connection.getContentEncoding()))); Closeables.closeQuietly(l_stream); return l_return; }
From source file:com.iStudy.Study.Renren.Util.java
public static String uploadFile(String reqUrl, Bundle parameters, String fileParamName, String filename, String contentType, byte[] data) { HttpURLConnection urlConn = null; try {//from w w w.jav a2 s. c o m urlConn = sendFormdata(reqUrl, parameters, fileParamName, filename, contentType, data); String responseContent = read(urlConn.getInputStream()); return responseContent.trim(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } finally { if (urlConn != null) { urlConn.disconnect(); } } }
From source file:com.cyphermessenger.client.SyncRequest.java
public static CypherSession userLogin(String username, byte[] serverPassword, byte[] localPassword) throws IOException, APIErrorException { String passwordHashEncoded = Utils.BASE64_URL.encode(serverPassword); HttpURLConnection conn = doRequest("login", null, new String[] { "username", "password" }, new String[] { username, passwordHashEncoded }); if (conn.getResponseCode() != 200) { throw new IOException("Server error"); }/* w w w . j a v a 2s.c o m*/ InputStream in = conn.getInputStream(); JsonNode node = MAPPER.readTree(in); conn.disconnect(); int statusCode = node.get("status").asInt(); if (statusCode == StatusCode.OK) { long userID = node.get("userID").asLong(); ECKey key; try { key = Utils.decodeKey(node.get("publicKey").asText(), node.get("privateKey").asText(), localPassword); } catch (InvalidCipherTextException ex) { throw new RuntimeException(ex); } long keyTimestamp = node.get("keyTimestamp").asLong(); key.setTime(keyTimestamp); CypherUser newUser = new CypherUser(username, localPassword, serverPassword, userID, key, keyTimestamp); String sessionID = node.get("sessionID").asText(); return new CypherSession(newUser, sessionID); } else { throw new APIErrorException(statusCode); } }
From source file:com.android.tools.idea.structure.MavenDependencyLookupDialog.java
@NotNull private static List<String> searchMavenCentral(@NotNull String text) { try {//w ww . j a va 2 s .co m String url = String.format(MAVEN_CENTRAL_SEARCH_URL, RESULT_LIMIT, text); final HttpURLConnection urlConnection = HttpConfigurable.getInstance().openHttpConnection(url); urlConnection.setConnectTimeout(SEARCH_TIMEOUT); urlConnection.setReadTimeout(SEARCH_TIMEOUT); urlConnection.setRequestProperty("accept", "application/xml"); InputStream inputStream = urlConnection.getInputStream(); Document document; try { document = new SAXBuilder().build(inputStream); } finally { inputStream.close(); } XPath idPath = XPath.newInstance("str[@name='id']"); XPath versionPath = XPath.newInstance("str[@name='latestVersion']"); List<Element> artifacts = (List<Element>) XPath.newInstance("/response/result/doc") .selectNodes(document); List<String> results = Lists.newArrayListWithExpectedSize(artifacts.size()); for (Element element : artifacts) { try { String id = ((Element) idPath.selectSingleNode(element)).getValue(); String version = ((Element) versionPath.selectSingleNode(element)).getValue(); results.add(id + ":" + version); } catch (NullPointerException e) { // A result is missing an ID or version. Just skip it. } } return results; } catch (JDOMException e) { LOG.warn(e); } catch (IOException e) { LOG.warn(e); } return Collections.emptyList(); }
From source file:mashberry.com500px.util.Api_Parser.java
/******************************************************************************* * /*from w w w. j av a 2 s . co m*/ * ( ) * *******************************************************************************/ public static String get_first_detail(final String url_feature, final int url_image_size, final String url_category, final int url_page, int image_no) { String returnStr = "success"; String urlStr = DB.Get_Photo_Url + "?feature=" + url_feature + "&image_size=" + url_image_size + "&only=" + getCategoryName(url_category) + "&page=" + url_page + "&consumer_key=" + Var.consumer_key + "&rpp=" + image_no; try { URL url = new URL(urlStr); URLConnection uc = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) uc; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setConnectTimeout(10000); httpConn.setRequestMethod("GET"); httpConn.connect(); int response = httpConn.getResponseCode(); Main.progressBar_process(50); if (response == HttpURLConnection.HTTP_OK) { InputStream in = httpConn.getInputStream(); String smallImageOpt = "3"; // (8 1/8 ) String largeImageOpt = "0"; String userPictureOpt = "8"; String result = convertStreamToString(in); JSONObject jObject = new JSONObject(result); JSONArray jsonArray = jObject.getJSONArray("photos"); Main.progressBar_process(75); if (jsonArray.length() == 0) { returnStr = "no results"; } else { for (int i = 0; i < jsonArray.length(); i++) { Var.categoryArr.add(jsonArray.getJSONObject(i).getString("category")); Var.idArr.add(jsonArray.getJSONObject(i).getString("id")); String smallImage = jsonArray.getJSONObject(i).getString("image_url"); String largeImage = largeImageOpt + smallImage.substring(0, smallImage.lastIndexOf(".jpg") - 1) + "4.jpg"; Var.imageSmall_urlArr.add(smallImageOpt + smallImage); Var.imageLarge_urlArr.add(largeImage); Var.nameArr.add(jsonArray.getJSONObject(i).getString("name")); Var.ratingArr.add(jsonArray.getJSONObject(i).getString("rating")); JSONObject jsonuser = jsonArray.getJSONObject(i).getJSONObject("user"); Var.user_firstnameArr.add(jsonuser.getString("firstname")); Var.user_fullnameArr.add(jsonuser.getString("fullname")); Var.user_lastnameArr.add(jsonuser.getString("lastname")); Var.user_upgrade_statusArr.add(jsonuser.getString("upgrade_status")); Var.user_usernameArr.add(jsonuser.getString("username")); Var.user_userpic_urlArr.add(userPictureOpt + jsonuser.getString("userpic_url")); Main.progressBar_process(75 + (15 * i / jsonArray.length())); } } // Log.i("Main", "urlStr " +urlStr); // Log.i("Main", "url_feature " +url_feature); // Log.i("Main", "categoryArr " +Var.categoryArr); // Log.i("Main", "idArr " +Var.idArr); // Log.i("Main", "imageLarge_urlArr " +Var.imageLarge_urlArr); // Log.i("Main", "nameArr " +Var.nameArr); // Log.i("Main", "ratingArr " +Var.ratingArr); // Log.i("Main", "user_firstnameArr " +Var.user_firstnameArr); // Log.i("Main", "user_fullnameArr " +Var.user_fullnameArr); // Log.i("Main", "user_lastnameArr " +Var.user_lastnameArr); // Log.i("Main", "user_upgrade_statusArr " +Var.user_upgrade_statusArr); // Log.i("Main", "user_usernameArr " +Var.user_usernameArr); // Log.i("Main", "user_userpic_urlArr " +Var.user_userpic_urlArr); } else { returnStr = "not response"; return returnStr; } } catch (Exception e) { e.printStackTrace(); returnStr = "not response"; return returnStr; } return returnStr; }
From source file:com.iStudy.Study.Renren.Util.java
public static byte[] getBytes(String url, Bundle params) { try {// ww w . j av a 2s .c om HttpURLConnection conn = openConn(url, "post", params); ByteArrayOutputStream os = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; InputStream is = conn.getInputStream(); for (int i = 0; (i = is.read(buf)) > 0;) { os.write(buf, 0, i); } is.close(); os.close(); return os.toByteArray(); } catch (Exception e) { Log.e(LOG_TAG, e.getMessage()); throw new RuntimeException(e.getMessage(), e); } }
From source file:com.hichinaschool.flashcards.anki.web.HttpFetcher.java
public static String downloadFileToSdCardMethod(String UrlToFile, Context context, String prefix, String method) {/* www.ja va 2s . c om*/ try { URL url = new URL(UrlToFile); String extension = UrlToFile.substring(UrlToFile.length() - 4); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod(method); urlConnection.setRequestProperty("Referer", "com.hichinaschool.flashcards.anki"); urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) "); urlConnection.setRequestProperty("Accept", "*/*"); urlConnection.connect(); File file = File.createTempFile(prefix, extension, DiskUtil.getStoringDirectory()); FileOutputStream fileOutput = new FileOutputStream(file); InputStream inputStream = urlConnection.getInputStream(); byte[] buffer = new byte[1024]; int bufferLength = 0; while ((bufferLength = inputStream.read(buffer)) > 0) { fileOutput.write(buffer, 0, bufferLength); } fileOutput.close(); return file.getAbsolutePath(); } catch (Exception e) { return "FAILED " + e.getMessage(); } }