List of usage examples for java.net HttpURLConnection getResponseCode
public int getResponseCode() throws IOException
From source file:de.jdellay.wallet.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> requestExchangeRates(final URL url, float ccnBtcConversion, final String userAgent, final String source, final String... fields) { final long start = System.currentTimeMillis(); HttpURLConnection connection = null; Reader reader = null;//from ww w . j av a 2 s . c o m try { connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.addRequestProperty("User-Agent", userAgent); connection.addRequestProperty("Accept-Encoding", "gzip"); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { final String contentEncoding = connection.getContentEncoding(); InputStream is = new BufferedInputStream(connection.getInputStream(), 1024); if ("gzip".equalsIgnoreCase(contentEncoding)) is = new GZIPInputStream(is); reader = new InputStreamReader(is, Constants.UTF_8); final StringBuilder content = new StringBuilder(); final long length = Io.copy(reader, content); final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); final JSONObject head = new JSONObject(content.toString()); for (final Iterator<String> i = head.keys(); i.hasNext();) { final String currencyCode = i.next(); if (!"timestamp".equals(currencyCode)) { final JSONObject o = head.getJSONObject(currencyCode); for (final String field : fields) { final String rate = o.optString(field, null); if (rate != null) { try { BigDecimal btcRate = new BigDecimal(GenericUtils.toNanoCoins(rate, 0)); BigInteger ccnRate = btcRate.multiply(BigDecimal.valueOf(ccnBtcConversion)) .toBigInteger(); if (ccnRate.signum() > 0) { rates.put(currencyCode, new ExchangeRate(currencyCode, ccnRate, source)); break; } } catch (final ArithmeticException x) { log.warn("problem fetching {} exchange rate from {} ({}): {}", currencyCode, url, contentEncoding, x.getMessage()); } } } } } log.info("fetched exchange rates from {} ({}), {} chars, took {} ms", url, contentEncoding, length, System.currentTimeMillis() - start); return rates; } else { log.warn("http status {} when fetching {}", responseCode, url); } } catch (final Exception x) { log.warn("problem fetching exchange rates from " + url, x); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } return null; }
From source file:main.java.vasolsim.common.GenericUtils.java
/** * Returns if a given http based address can be connected to * * @param address the address/* ww w. j a v a2 s. c o m*/ * * @return if teh connection can be made */ public static boolean canConnectToAddress(String address) { if (!isValidAddress(address)) return false; try { HttpURLConnection connection = (HttpURLConnection) (new URL(address).openConnection()); connection.setRequestMethod("HEAD"); connection.connect(); boolean success = (connection.getResponseCode() == HttpURLConnection.HTTP_OK); connection.disconnect(); return success; } catch (Exception e) { return false; } }
From source file:core.Web.java
public static String httpRequest(URL url, Map<String, String> properties, JSONObject message) { // System.out.println(url); try {//from ww w . j a v a 2s. c om // Create connection HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //connection.addRequestProperty("Authorization", API_KEY); // Set properties if needed if (properties != null && !properties.isEmpty()) { properties.forEach(connection::setRequestProperty); } // Post message if (message != null) { // Maybe somewhere connection.setDoOutput(true); // connection.setRequestProperty("Accept", "application/json"); try (BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(connection.getOutputStream()))) { writer.write(message.toString()); } } // Establish connection connection.connect(); int responseCode = connection.getResponseCode(); if (responseCode != 200) { System.err.println("Error " + responseCode + ":" + url); return null; } try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { String line; String content = ""; while ((line = reader.readLine()) != null) { content += line; } return content; } } catch (IOException ex) { Logger.getLogger(Web.class.getName()).log(Level.SEVERE, null, ex); } return null; }
From source file:net.bible.service.common.CommonUtils.java
/** return true if URL is accessible * /*from w ww . ja v a 2 s.c om*/ * Since Android 3 must do on different or NetworkOnMainThreadException is thrown */ public static boolean isHttpUrlAvailable(final String urlString) { boolean isAvailable = false; final int TIMEOUT_MILLIS = 3000; try { class CheckUrlThread extends Thread { public boolean checkUrlSuccess = false; public void run() { HttpURLConnection connection = null; try { // might as well test for the url we need to access URL url = new URL(urlString); Log.d(TAG, "Opening test connection"); connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(TIMEOUT_MILLIS); Log.d(TAG, "Connecting to test internet connection"); connection.connect(); checkUrlSuccess = (connection.getResponseCode() == HttpURLConnection.HTTP_OK); Log.d(TAG, "Url test result for:" + urlString + " is " + checkUrlSuccess); } catch (IOException e) { Log.i(TAG, "No internet connection"); checkUrlSuccess = false; } finally { if (connection != null) { connection.disconnect(); } } } } ; CheckUrlThread checkThread = new CheckUrlThread(); checkThread.start(); checkThread.join(TIMEOUT_MILLIS); isAvailable = checkThread.checkUrlSuccess; } catch (InterruptedException e) { Log.e(TAG, "Interrupted waiting for url check to complete", e); } return isAvailable; }
From source file:com.binil.pushnotification.ServerUtil.java
/** * Issue a POST request to the server./*from w w w . j a v a2 s. co m*/ * * @param endpoint POST address. * @param params request parameters. * @throws java.io.IOException propagated from POST. */ private static void post(String endpoint, Map<String, Object> params) throws IOException, JSONException { URL url = new URL(endpoint); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("Cache-Control", "no-cache"); urlConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8"); urlConnection.setRequestProperty("Accept-Encoding", "gzip,deflate"); urlConnection.setRequestProperty("Accept", "*/*"); urlConnection.setDoOutput(true); JSONObject json = new JSONObject(params); String body = json.toString(); urlConnection.setFixedLengthStreamingMode(body.length()); try { OutputStream os = urlConnection.getOutputStream(); os.write(body.getBytes("UTF-8")); os.close(); } catch (Exception e) { e.printStackTrace(); } finally { int status = urlConnection.getResponseCode(); String connectionMsg = urlConnection.getResponseMessage(); urlConnection.disconnect(); if (status != HttpURLConnection.HTTP_OK) { Log.wtf(TAG, connectionMsg); throw new IOException("Post failed with error code " + status); } } }
From source file:com.createtank.payments.coinbase.RequestClient.java
private static JsonObject call(CoinbaseApi api, String method, RequestVerb verb, Map<String, String> params, boolean retry, String accessToken) throws IOException { if (api.allowSecure()) { HttpClient client = HttpClientBuilder.create().build(); String url = BASE_URL + method; HttpUriRequest request = null;//from w w w . java2 s . co m if (verb == RequestVerb.POST || verb == RequestVerb.PUT) { switch (verb) { case POST: request = new HttpPost(url); break; case PUT: request = new HttpPut(url); break; default: throw new RuntimeException("RequestVerb not implemented: " + verb); } List<BasicNameValuePair> paramsBody = new ArrayList<BasicNameValuePair>(); if (params != null) { List<BasicNameValuePair> convertedParams = convertParams(params); paramsBody.addAll(convertedParams); } ((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(paramsBody, "UTF-8")); } else { if (params != null) { url = url + "?" + createRequestParams(params); } if (verb == RequestVerb.GET) { request = new HttpGet(url); } else if (verb == RequestVerb.DELETE) { request = new HttpDelete(url); } } if (request == null) return null; if (accessToken != null) request.addHeader("Authorization", String.format("Bearer %s", accessToken)); System.out.println("auth header: " + request.getFirstHeader("Authorization")); HttpResponse response = client.execute(request); int code = response.getStatusLine().getStatusCode(); if (code == 401) { if (retry) { api.refreshAccessToken(); call(api, method, verb, params, false, api.getAccessToken()); } else { throw new IOException("Account is no longer valid"); } } else if (code != 200) { throw new IOException("HTTP response " + code + " to request " + method); } String responseString = EntityUtils.toString(response.getEntity()); if (responseString.startsWith("[")) { // Is an array responseString = "{response:" + responseString + "}"; } JsonParser parser = new JsonParser(); JsonObject resp = (JsonObject) parser.parse(responseString); System.out.println(resp.toString()); return resp; } String paramStr = createRequestParams(params); String url = BASE_URL + method; if (paramStr != null && verb == RequestVerb.GET || verb == RequestVerb.DELETE) url += "?" + paramStr; HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod(verb.name()); if (accessToken != null) conn.setRequestProperty("Authorization", String.format("Bearer %s", accessToken)); if (verb != RequestVerb.GET && verb != RequestVerb.DELETE && paramStr != null) { conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(paramStr); writer.flush(); writer.close(); } int code = conn.getResponseCode(); if (code == 401) { if (retry) { api.refreshAccessToken(); return call(api, method, verb, params, false, api.getAccessToken()); } else { throw new IOException("Account is no longer valid"); } } else if (code != 200) { throw new IOException("HTTP response " + code + " to request " + method); } String responseString = getResponseBody(conn.getInputStream()); if (responseString.startsWith("[")) { responseString = "{response:" + responseString + "}"; } JsonParser parser = new JsonParser(); return (JsonObject) parser.parse(responseString); }
From source file:de.schildbach.wallet.goldcoin.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> getBitcoinCharts() { try {//from w w w .jav a 2 s . c o m // double btcRate = getGoldCoinValueBTC(); //NullPointerException??? Double btcRate = 0.0; Object result = getGoldCoinValueBTC_ccex(); if (result == null) { result = getCoinValueBTC_cryptopia(); if (result == null) return null; else btcRate = (Double) result; } else btcRate = (Double) result; final URL URL = new URL("http://api.bitcoincharts.com/v1/weighted_prices.json"); final HttpURLConnection connection = (HttpURLConnection) URL.openConnection(); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.connect(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) return null; Reader reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024)); final StringBuilder content = new StringBuilder(); IOUtils.copy(reader, content); final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); //Add Bitcoin information rates.put("BTC", new ExchangeRate("BTC", Utils.toNanoCoins(String.format("%.8f", btcRate).replace(",", ".")), "pubapi.cryptsy.com")); final JSONObject head = new JSONObject(content.toString()); for (final Iterator<String> i = head.keys(); i.hasNext();) { final String currencyCode = i.next(); if (!"timestamp".equals(currencyCode)) { final JSONObject o = head.getJSONObject(currencyCode); String rate = o.optString("24h", null); if (rate == null) rate = o.optString("7d", null); if (rate == null) rate = o.optString("30d", null); double rateForBTC = Double.parseDouble(rate); rate = String.format("%.8f", rateForBTC * btcRate); if (rate != null) rates.put(currencyCode, new ExchangeRate(currencyCode, Utils.toNanoCoins(rate.replace(",", ".")), URL.getHost())); } } return rates; } finally { if (reader != null) reader.close(); } } catch (final IOException x) { // log.debug("problem reading exchange rates", x); x.printStackTrace(); } catch (final JSONException x) { //log.debug("problem reading exchange rates", x); x.printStackTrace(); } return null; }
From source file:bluevia.SendSMS.java
public static void setFacebookWallPost(String userEmail, String post) { try {/*from w w w . ja v a 2 s. c o m*/ Properties facebookAccount = Util.getNetworkAccount(userEmail, Util.FaceBookOAuth.networkID); if (facebookAccount != null) { String access_key = facebookAccount.getProperty(Util.FaceBookOAuth.networkID + ".access_key"); com.google.appengine.api.urlfetch.FetchOptions.Builder.doNotValidateCertificate(); Entity blueviaUser = Util.getUser(userEmail); //FIXME URL fbAPI = new URL( "https://graph.facebook.com/" + (String) blueviaUser.getProperty("alias") + "/feed"); HttpURLConnection request = (HttpURLConnection) fbAPI.openConnection(); String content = String.format("access_token=%s&message=%s", access_key, URLEncoder.encode(post, "UTF-8")); request.setRequestMethod("POST"); request.setRequestProperty("Content-Type", "javascript/text"); request.setRequestProperty("Content-Length", "" + Integer.toString(content.getBytes().length)); request.setDoOutput(true); request.setDoInput(true); OutputStream os = request.getOutputStream(); os.write(content.getBytes()); os.flush(); os.close(); BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); int rc = request.getResponseCode(); if (rc == HttpURLConnection.HTTP_OK) { StringBuffer body = new StringBuffer(); String line; do { line = br.readLine(); if (line != null) body.append(line); } while (line != null); JSONObject id = new JSONObject(body.toString()); } else log.severe( String.format("Error %d posting FaceBook wall:%s\n", rc, request.getResponseMessage())); } } catch (Exception e) { log.severe(String.format("Exception posting FaceBook wall: %s", e.getMessage())); } }
From source file:com.ant.myteam.gcm.POST2GCM.java
public static void post(String apiKey, Content content) { try {//w ww .ja v a 2 s. c om // 1. URL URL url = new URL("https://android.googleapis.com/gcm/send"); // 2. Open connection HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 3. Specify POST method conn.setRequestMethod("POST"); // 4. Set the headers conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Authorization", "key=" + apiKey); conn.setDoOutput(true); // 5. Add JSON data into POST request body //`5.1 Use Jackson object mapper to convert Contnet object into JSON ObjectMapper mapper = new ObjectMapper(); // 5.2 Get connection output stream DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); // 5.3 Copy Content "JSON" into mapper.writeValue(wr, content); // 5.4 Send the request wr.flush(); // 5.5 close wr.close(); // 6. Get the response int responseCode = conn.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 7. Print result System.out.println(response.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:pushandroid.POST2GCM.java
public static void post(Content content) { try {// w w w . j a v a2 s .c o m // 1. URL URL url = new URL(URL); // 2. Open connection HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 3. Specify POST method conn.setRequestMethod("POST"); // 4. Set the headers conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Authorization", "key=" + apiKey); conn.setDoOutput(true); // 5. Add JSON data into POST request body //`5.1 Use Jackson object mapper to convert Contnet object into JSON ObjectMapper mapper = new ObjectMapper(); // 5.2 Get connection output stream DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); // 5.3 Copy Content "JSON" into mapper.writeValue(wr, content); // 5.4 Send the request wr.flush(); // 5.5 close wr.close(); // 6. Get the response int responseCode = conn.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 7. Print result System.out.println(response.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }