List of usage examples for java.net HttpURLConnection getInputStream
public InputStream getInputStream() throws IOException
From source file:com.chiorichan.util.WebUtils.java
/** * Opens an HTTP connection to a web URL and tests that the response is a valid 200-level code * and we can successfully open a stream to the content. * //from w ww . j a v a2 s . c om * @param url * The HTTP URL indicating the location of the content. * @return True if the content can be accessed successfully, false otherwise. */ public static boolean pingHttpURL(String url) { InputStream stream = null; try { final HttpURLConnection conn = openHttpConnection(new URL(url)); conn.setConnectTimeout(10000); int responseCode = conn.getResponseCode(); int responseFamily = responseCode / 100; if (responseFamily == 2) { stream = conn.getInputStream(); IOUtils.closeQuietly(stream); return true; } else { return false; } } catch (IOException e) { return false; } finally { IOUtils.closeQuietly(stream); } }
From source file:edu.dartmouth.cs.dartcard.HttpUtilities.java
public static String get(String endpoint, Map<String, String> params) { URL url = null;//from w ww . jav a 2 s.com try { url = new URL(endpoint); } catch (MalformedURLException e) { //Fail silently } byte[] bytes = constructParams(params); HttpURLConnection conn; long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000); for (int i = 1; i <= HttpUtilities.MAX_ATTEMPTS; i++) { try { conn = makeGetConnection(url, bytes); // handle the response int status = conn.getResponseCode(); if (status == 200) { BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); if (null != conn) { conn.disconnect(); } return sb.toString(); } else if (500 > status) { if (null != conn) { conn.disconnect(); } return null; } } catch (IOException e) { try { Thread.sleep(backoff); } catch (InterruptedException e1) { // Activity finished before we complete - exit. Thread.currentThread().interrupt(); } // increase backoff exponentially backoff *= 2; } } return null; }
From source file:com.appsimobile.appsii.module.weather.loader.YahooWeatherApiClient.java
@Nullable public static CircularArray<WeatherData> getWeatherForWoeids(CircularArray<String> woeids, String unit) throws CantGetWeatherException { if (woeids == null || woeids.isEmpty()) return null; HttpURLConnection connection = null; try {/*from ww w . ja v a 2 s. c o m*/ String url = buildWeatherQueryUrl(woeids, unit); if (BuildConfig.DEBUG) Log.d("YahooWeatherApiClient", "loading weather from: " + url); connection = Utils.openUrlConnection(url); CircularArray<WeatherData> result = new CircularArray<>(); WeatherDataParser.parseWeatherData(result, connection.getInputStream(), woeids); return result; } catch (JSONException | ResponseParserException | ParseException | IOException | NumberFormatException e) { throw new CantGetWeatherException(true, R.string.no_weather_data, "Error parsing weather feed XML.", e); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:com.github.thorqin.webapi.oauth2.OAuthClient.java
public static AccessToken obtainAccessTokenByCode(String authorityServerUri, String clientId, String clientSecret, String code, String redirectUri, boolean useBasicAuthentication) throws IOException, OAuthException { String rawData = makeObtainAccessTokenByCode(clientId, clientSecret, code, redirectUri, useBasicAuthentication);/*from w ww. j a v a 2 s . co m*/ String type = "application/x-www-form-urlencoded"; URL u = new URL(authorityServerUri); HttpURLConnection conn = (HttpURLConnection) u.openConnection(); conn.setDoOutput(true); if (useBasicAuthentication) { String basicAuthentication = Base64.encodeBase64String((clientId + ":" + clientSecret).getBytes()); conn.setRequestProperty("Authorization", "Basic " + basicAuthentication); } conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", type); conn.setRequestProperty("Content-Length", String.valueOf(rawData.length())); try (OutputStream os = conn.getOutputStream()) { os.write(rawData.getBytes()); } try (InputStream is = conn.getInputStream(); InputStreamReader reader = new InputStreamReader(is)) { AccessTokenResponse token = Serializer.fromJson(reader, AccessTokenResponse.class); if (token.error != null) { throw new OAuthException(token.error, token.errorDescription, token.errorUri); } return token; } }
From source file:edu.dartmouth.cs.dartcard.HttpUtilities.java
/** * Issue a POST request to the server, and return the results from it as a string * /*from ww w. java2s.c om*/ * @param endpoint * POST address. * @param params * request parameters. * * @throws IOException * propagated from POST. */ public static String postForResults(String endpoint, Map<String, String> params) { URL url = null; try { url = new URL(endpoint); } catch (MalformedURLException e) { //Fail silently } byte[] bytes = constructParams(params); HttpURLConnection conn; long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000); for (int i = 1; i <= HttpUtilities.MAX_ATTEMPTS; i++) { try { conn = makePostConnection(url, bytes); // handle the response int status = conn.getResponseCode(); if (status == 200) { BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); if (null != conn) { conn.disconnect(); } return sb.toString(); } else if (500 > status) { if (null != conn) { conn.disconnect(); } return null; } } catch (IOException e) { try { Thread.sleep(backoff); } catch (InterruptedException e1) { // Activity finished before we complete - exit. Thread.currentThread().interrupt(); } // increase backoff exponentially backoff *= 2; } } return null; }
From source file:a122016.rr.com.alertme.QueryUtils.java
/** * Make an HTTP request to the given URL and return a String as the response. */// ww w. ja v a 2s. 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 { Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode()); } } catch (IOException e) { Log.e(LOG_TAG, "Problem retrieving the Places JSON results.", e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (inputStream != null) { // Closing the input stream could throw an IOException, which is why // the makeHttpRequest(URL url) method signature specifies than an IOException // could be thrown. inputStream.close(); } } return jsonResponse; }
From source file:com.openforevent.main.UserPosition.java
public static Map<String, Object> userLocationProperties(DispatchContext ctx, Map<String, ? extends Object> context) throws IOException { Delegator delegator = ctx.getDelegator(); LocalDispatcher dispatcher = ctx.getDispatcher(); String visitId = (String) context.get("visitId"); if (Debug.infoOn()) { Debug.logInfo("In userLocationProperties", module); }/* ww w .j a v a2s.c om*/ // get user coords coordsOfUserPosition(ctx, context); URL url = new URL( "https://graph.facebook.com/search?since=now&limit=4&q=2012-05-07&type=event&access_token=" + "AAACEdEose0cBAN9CB2ErxVN3JvK2gsrLslPt6e6Y7hJ0OrMEkMoyNwvHgSZCAEu2lCHZALlVWXZCW5JL8asMWoaPN3UAXFpZBsJJ6SvXRAAIZAXeTo0fD"); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); // Set properties of the connection urlConnection.setRequestMethod("GET"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setUseCaches(false); urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // Retrieve the output int responseCode = urlConnection.getResponseCode(); InputStream inputStream; if (responseCode == HttpURLConnection.HTTP_OK) { inputStream = urlConnection.getInputStream(); } else { inputStream = urlConnection.getErrorStream(); } StringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer, "UTF-8"); String theString = writer.toString(); Debug.logInfo("Facebook stream = ", theString); if (theString.contains("AuthException") == true) { url = new URL("https://graph.facebook.com/oauth/access_token?" + "client_id= 283576871735609&" + "client_secret= 5cf1fe4e531dff8de228bfac61b8fdfa&" + "grant_type=fb_exchange_token&" + "fb_exchange_token=" + "AAACEdEose0cBAN9CB2ErxVN3JvK2gsrLslPt6e6Y7hJ0OrMEkMoyNwvHgSZCAEu2lCHZALlVWXZCW5JL8asMWoaPN3UAXFpZBsJJ6SvXRAAIZAXeTo0fD"); HttpURLConnection urlConnection1 = (HttpURLConnection) url.openConnection(); // Set properties of the connection urlConnection1.setRequestMethod("GET"); urlConnection1.setDoInput(true); urlConnection1.setDoOutput(true); urlConnection1.setUseCaches(false); urlConnection1.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // Retrieve the output int responseCode1 = urlConnection1.getResponseCode(); InputStream inputStream1; if (responseCode == HttpURLConnection.HTTP_OK) { inputStream1 = urlConnection1.getInputStream(); } else { inputStream1 = urlConnection1.getErrorStream(); } StringWriter writer1 = new StringWriter(); IOUtils.copy(inputStream1, writer1, "UTF-8"); String theString1 = writer1.toString(); Debug.logInfo("Facebook stream1 = ", theString1); } Map<String, Object> paramOut = FastMap.newInstance(); paramOut.put("geoName", "aaa"); paramOut.put("abbreviation", "bbb"); return paramOut; }
From source file:com.fastbootmobile.encore.api.common.HttpGet.java
/** * Downloads the data from the provided URL. * @param inUrl The URL to get from/* ww w . j a v a 2 s . co m*/ * @param query The query field. '?' + query will be appended automatically, and the query data * MUST be encoded properly. * @return A byte array of the data */ public static byte[] getBytes(String inUrl, String query, boolean cached) throws IOException, RateLimitException { final String formattedUrl = inUrl + (query.isEmpty() ? "" : ("?" + query)); Log.d(TAG, "Formatted URL: " + formattedUrl); URL url = new URL(formattedUrl); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", "OmniMusic/1.0-dev (http://www.omnirom.org)"); urlConnection.setUseCaches(cached); urlConnection.setInstanceFollowRedirects(true); int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale urlConnection.addRequestProperty("Cache-Control", "max-stale=" + maxStale); try { final int status = urlConnection.getResponseCode(); // MusicBrainz returns 503 Unavailable on rate limit errors. Parse the JSON anyway. if (status == HttpURLConnection.HTTP_OK) { InputStream in = new BufferedInputStream(urlConnection.getInputStream()); int contentLength = urlConnection.getContentLength(); if (contentLength <= 0) { // No length? Let's allocate 100KB. contentLength = 100 * 1024; } ByteArrayBuffer bab = new ByteArrayBuffer(contentLength); BufferedInputStream bis = new BufferedInputStream(in); int character; while ((character = bis.read()) != -1) { bab.append(character); } return bab.toByteArray(); } else if (status == HttpURLConnection.HTTP_NOT_FOUND) { // 404 return new byte[] {}; } else if (status == HttpURLConnection.HTTP_FORBIDDEN) { return new byte[] {}; } else if (status == HttpURLConnection.HTTP_UNAVAILABLE) { throw new RateLimitException(); } else if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == 307 /* HTTP/1.1 TEMPORARY REDIRECT */ || status == HttpURLConnection.HTTP_SEE_OTHER) { // We've been redirected, follow the new URL final String followUrl = urlConnection.getHeaderField("Location"); Log.e(TAG, "Redirected to: " + followUrl); return getBytes(followUrl, "", cached); } else { Log.e(TAG, "Error when fetching: " + formattedUrl + " (" + urlConnection.getResponseCode() + ")"); return new byte[] {}; } } finally { urlConnection.disconnect(); } }
From source file:com.fluidops.iwb.luxid.LuxidExtractor.java
public static String useLuxidWS(String input, String token, String outputFormat, String annotationPlan) throws Exception { String s = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=" + "\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> " + "<SOAP-ENV:Body> <ns1:annotateString xmlns:ns1=\"http://luxid.temis.com/ws/types\"> " + "<ns1:sessionKey>" + token + "</ns1:sessionKey> <ns1:plan>" + annotationPlan + "</ns1:plan> <ns1:data>"; s += input;// "This is a great providing test"; s += "</ns1:data> <ns1:consumer>" + outputFormat + "</ns1:consumer> </ns1:annotateString> </SOAP-ENV:Body> " + "</SOAP-ENV:Envelope>"; URL url = new URL("http://193.104.205.28//LuxidWS/services/Annotation"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true);// ww w . ja v a 2 s . c om conn.getOutputStream().write(s.getBytes()); StringBuilder res = new StringBuilder(); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream stream = conn.getInputStream(); InputStreamReader read = new InputStreamReader(stream); BufferedReader rd = new BufferedReader(read); String line = ""; StringEscapeUtils.escapeHtml(""); while ((line = rd.readLine()) != null) { res.append(line); } rd.close(); } // res = URLDecoder.decode(res, "UTF-8"); return StringEscapeUtils.unescapeHtml(res.toString().replace("&lt", "<")); }
From source file:gov.nasa.arc.geocam.geocam.HttpPost.java
public static String postFiles(String url, Map<String, String> vars, Map<String, File> files) { try {//from ww w.ja va2s . c om HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); assembleMultipartFiles(out, vars, files); InputStream in = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } return sb.toString(); } catch (UnsupportedEncodingException e) { return "Encoding exception: " + e; } catch (IOException e) { return "IOException: " + e; } catch (IllegalStateException e) { return "IllegalState: " + e; } }