List of usage examples for java.net HttpURLConnection getResponseCode
public int getResponseCode() 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. * //w w w . j a v a2 s . c o m * @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:com.zf.util.Post_NetNew.java
public static String pn(Map<String, String> pams) throws Exception { if (null == pams) { return ""; }/*w w w. j a v a 2s . c o m*/ String strtmp = "url"; URL url = new URL(pams.get(strtmp)); pams.remove(strtmp); strtmp = "body"; String body = pams.get(strtmp); pams.remove(strtmp); strtmp = "POST"; if (StringUtils.isEmpty(body)) strtmp = "GET"; HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.setUseCaches(false); httpConn.setRequestMethod(strtmp); for (String pam : pams.keySet()) { httpConn.setRequestProperty(pam, pams.get(pam)); } if ("POST".equals(strtmp)) { httpConn.setDoOutput(true); httpConn.setDoInput(true); DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream()); dos.writeBytes(body); dos.flush(); } int resultCode = httpConn.getResponseCode(); StringBuilder sb = new StringBuilder(); sb.append(resultCode).append("\n"); String readLine; InputStream stream; try { stream = httpConn.getInputStream(); } catch (Exception ignored) { stream = httpConn.getErrorStream(); } try { BufferedReader responseReader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); while ((readLine = responseReader.readLine()) != null) { sb.append(readLine).append("\n"); } } catch (Exception ignored) { } return sb.toString(); }
From source file:com.adanac.module.blog.api.HttpApiHelper.java
public static void baiduPush(int remain) { String pushUrl = DaoFactory.getDao(HtmlPageDao.class).findPushUrl(); if (pushUrl == null) { if (logger.isInfoEnabled()) { logger.info("all html page has been pushed!"); }/*from w ww .j a va 2 s . c om*/ return; } if (remain <= 0) { if (logger.isInfoEnabled()) { logger.info("there has no remain[" + remain + "]!"); } return; } if (logger.isInfoEnabled()) { logger.info("find push url : " + pushUrl); } String url = "http://data.zz.baidu.com/urls?site=" + site + "&token=" + token; try { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "text/plain"); OutputStream outputStream = connection.getOutputStream(); outputStream.write(pushUrl.getBytes("UTF-8")); outputStream.write("\r\n".getBytes("UTF-8")); outputStream.flush(); int status = connection.getResponseCode(); if (logger.isInfoEnabled()) { logger.info("baidu-push response code : " + status); } if (status == HttpServletResponse.SC_OK) { String response = IOUtil.read(connection.getInputStream()); if (logger.isInfoEnabled()) { logger.info("baidu-push response : " + response); } JSONObject result = JSONObject.fromObject(response); if (result.getInt("success") >= 1) { DaoFactory.getDao(HtmlPageDao.class).updateIsPush(pushUrl); } else { logger.warn("push url failed : " + pushUrl); } baiduPush(result.getInt("remain")); } else { logger.error("baidu-push error : " + IOUtil.read(connection.getErrorStream())); } } catch (Exception e) { logger.error("baidu push failed ...", e); } }
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); }/*www.j a v a2 s. co m*/ // 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:edu.dartmouth.cs.dartcard.HttpUtilities.java
public static String get(String endpoint, Map<String, String> params) { URL url = null;//w ww. j a v a 2s . c om 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:LNISmokeTest.java
/** * Get an item with WebDAV GET http request. * /*from ww w . ja va 2s . c o m*/ * @param lni the lni * @param itemHandle the item handle * @param packager the packager * @param output the output * @param endpoint the endpoint * * @throws RemoteException the remote exception * @throws ProtocolException the protocol exception * @throws IOException Signals that an I/O exception has occurred. * @throws FileNotFoundException the file not found exception */ private static void doGet(LNISoapServlet lni, String itemHandle, String packager, String output, String endpoint) throws java.rmi.RemoteException, ProtocolException, IOException, FileNotFoundException { // assemble URL from chopped endpoint-URL and relative URI String itemURI = doLookup(lni, itemHandle, null); URL url = LNIClientUtils.makeDAVURL(endpoint, itemURI, packager); System.err.println("DEBUG: GET from URL: " + url.toString()); // connect with GET method, then copy file over. HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoInput(true); fixBasicAuth(url, conn); conn.connect(); int status = conn.getResponseCode(); if (status < 200 || status >= 300) { die(status, "HTTP error, status=" + String.valueOf(status) + ", message=" + conn.getResponseMessage()); } InputStream in = conn.getInputStream(); OutputStream out = new FileOutputStream(output); copyStream(in, out); in.close(); out.close(); System.err.println("DEBUG: Created local file " + output); System.err.println( "RESULT: Status=" + String.valueOf(conn.getResponseCode()) + " " + conn.getResponseMessage()); }
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 * //ww w. j av a2 s . 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:hashengineering.digitalcoin.wallet.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> getBlockchainInfo() { try {/* w w w. ja v a2s .com*/ Double btcRate = 0.0; Object result = getCoinValueBTC(); if (result == null) return null; else btcRate = (Double) result; final URL URL = new URL("https://blockchain.info/ticker"); 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), Constants.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); //Add Bitcoin information rates.put(CoinDefinition.cryptsyMarketCurrency, new ExchangeRate(CoinDefinition.cryptsyMarketCurrency, 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(); final JSONObject o = head.getJSONObject(currencyCode); //final String rate = o.optString("15m", null); double rateForBTC = o.getDouble("15m") * btcRate; final String rate = String.format("%.8f", rateForBTC); //o.optString("15m", null); if (rate != null) { try { rates.put(currencyCode, new ExchangeRate(currencyCode, Utils.toNanoCoins(rate.replace(",", ".")), URL.getHost())); } catch (final ArithmeticException x) { log.debug("problem reading exchange rate: " + currencyCode, x); } } } return rates; } finally { if (reader != null) reader.close(); } } catch (final Exception x) { log.debug("problem reading exchange rates", x); } return null; }
From source file:com.magnet.plugin.common.helpers.URLHelper.java
public static String checkURLConnection(String urlS, String username, String password) { String status = "Error connection to server!"; FormattedLogger logger = new FormattedLogger(URLHelper.class); logger.append("checkURLConnection:" + urlS); try {//from w w w.j ava2 s . c om URL url = new URL(urlS); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (username != null && username.trim().length() > 0 && password != null && password.trim().length() > 0) { final String authString = username + ":" + password; conn.setRequestProperty("Authorization", "Basic " + Base64.encode(authString.getBytes())); } conn.setRequestMethod("GET"); conn.setDoInput(true); status = "" + conn.getResponseCode(); logger.append("Response code:" + status); logger.showInfoLog(); } catch (Exception e) { logger.append(">>>" + e.getClass().getName() + " message: " + e.getMessage()); logger.showErrorLog(); } return status; }
From source file:edu.dartmouth.cs.dartcard.HttpUtilities.java
/** * Issue a POST request to the server.//from w w w . j a va 2 s .c o m * * @param endpoint * POST address. * @param params * request parameters. * * @throws IOException * propagated from POST. */ public static boolean post(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) { //Useful for debugging /* 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(); Log.d("output", sb.toString()); */ if (null != conn) { conn.disconnect(); } return true; } else if (500 > status) { if (null != conn) { conn.disconnect(); } return false; } } 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 false; }