List of usage examples for java.net HttpURLConnection connect
public abstract void connect() throws IOException;
From source file:io.andyc.papercut.api.PrintApi.java
/** * Queries the remote Papercut server to get the status of the file * * e.g.//from w w w . j a v a2 s . c o m * * {"status":{"code":"hold-release","complete":false,"text":"Held in a * queue","formatted":"Held in a queue"},"documentName":"test.rtf", * "printer":"Floor1 (Full Colour)","pages":1,"cost":"$0.10"} * * @param printJob {PrintJob} - the file to check the status on * * @return {String} - JSON String which includes file metadata * * @throws NoStatusURLSetException * @throws IOException */ public static PrintStatusData getFileStatus(PrintJob printJob) throws NoStatusURLSetException, IOException { if (Objects.equals(printJob.getStatusCheckURL(), "") || printJob.getStatusCheckURL() == null) { throw new NoStatusURLSetException(); } // from: http://stackoverflow.com/a/29889139/2605221 StringBuilder stringBuffer = new StringBuilder(""); URL url = new URL(printJob.getStatusCheckURL()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("User-Agent", ""); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); connection.setDoInput(true); connection.connect(); InputStream inputStream = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream)); String line = ""; while ((line = rd.readLine()) != null) { stringBuffer.append(line); } return new ObjectMapper().readValue(stringBuffer.toString(), PrintStatusData.class); }
From source file:eu.geopaparazzi.library.network.NetworkUtilities.java
/** * Sends a string via POST to a given url. * //from w w w .j a va2 s .c o m * @param urlStr the url to which to send to. * @param string the string to send as post body. * @param user the user or <code>null</code>. * @param password the password or <code>null</code>. * @return the response. * @throws Exception */ public static String sendPost(String urlStr, String string, String user, String password) throws Exception { BufferedOutputStream wr = null; HttpURLConnection conn = null; try { conn = makeNewConnection(urlStr); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); // conn.setChunkedStreamingMode(0); conn.setUseCaches(false); if (user != null && password != null) { conn.setRequestProperty("Authorization", getB64Auth(user, password)); } conn.connect(); // Make server believe we are form data... wr = new BufferedOutputStream(conn.getOutputStream()); byte[] bytes = string.getBytes(); wr.write(bytes); wr.flush(); int responseCode = conn.getResponseCode(); StringBuilder returnMessageBuilder = new StringBuilder(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); while (true) { String line = br.readLine(); if (line == null) break; returnMessageBuilder.append(line + "\n"); } br.close(); } return returnMessageBuilder.toString(); } catch (Exception e) { e.printStackTrace(); throw e; } finally { if (conn != null) conn.disconnect(); } }
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 ava2 s . c om 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:in.neoandroid.neoupdate.neoUpdate.java
/** * A Simpler HTTPConnection helper./*from w w w . j av a2s .c o m*/ * Used currently. */ private static HttpURLConnection getHTTPConnection(String url) throws MalformedURLException, IOException { HttpURLConnection c; c = (HttpURLConnection) new URL(url).openConnection(); c.setUseCaches(false); c.connect(); return c; }
From source file:edu.stanford.epadd.launcher.Splash.java
private static boolean killRunningServer(String url) throws IOException { try {//from www. j ava 2s .c o m // attempt to fetch the page // throws a connect exception if the server is not even running // so catch it and return false String http = url + "/exit.jsp?message=Shutdown%20request%20from%20a%20different%20instance%20of%20ePADD"; // version num spaces and brackets screw up the URL connection out.println("Sending a kill request to " + http); HttpURLConnection u = (HttpURLConnection) new URL(http).openConnection(); u.connect(); if (u.getResponseCode() == 200) { u.disconnect(); return true; } u.disconnect(); } catch (ConnectException ce) { } return false; }
From source file:net.bible.service.common.CommonUtils.java
/** return true if URL is accessible * //from w ww .j a v a 2 s .c o m * 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:main.java.vasolsim.common.GenericUtils.java
/** * Returns if a given http based address can be connected to * * @param address the address/*from w w w .j a v a 2 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:Main.java
@TargetApi(Build.VERSION_CODES.KITKAT) public static String net(String strUrl, Map<String, Object> params, String method) throws Exception { HttpURLConnection conn = null; BufferedReader reader = null; String rs = null;//from w ww .j a va 2 s .c o m try { StringBuffer sb = new StringBuffer(); if (method == null || method.equals("GET")) { strUrl = strUrl + "?" + urlencode(params); } URL url = new URL(strUrl); conn = (HttpURLConnection) url.openConnection(); if (method == null || method.equals("GET")) { conn.setRequestMethod("GET"); } else { conn.setRequestMethod("POST"); conn.setDoOutput(true); } conn.setRequestProperty("User-agent", userAgent); conn.setUseCaches(false); conn.setConnectTimeout(DEF_CONN_TIMEOUT); conn.setReadTimeout(DEF_READ_TIMEOUT); conn.setInstanceFollowRedirects(false); conn.connect(); if (params != null && method.equals("POST")) { try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) { out.writeBytes(urlencode(params)); } } InputStream is = conn.getInputStream(); reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET)); String strRead = null; while ((strRead = reader.readLine()) != null) { sb.append(strRead); } rs = sb.toString(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { reader.close(); } if (conn != null) { conn.disconnect(); } } return rs; }
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 . jav a2s .c o m // 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:edu.stanford.muse.index.NER.java
/** returns a list of <name, #occurrences> */ public static List<Pair<String, Float>> namesFromURL(String url, boolean removeCommonNames) throws ClassCastException, IOException, ClassNotFoundException { // only http conns allowed currently Indexer.log.info(url);//from ww w .j a v a 2 s.co m HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setInstanceFollowRedirects(true); conn.setRequestProperty("User-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:6.0.2) Gecko/20100101 Firefox/6.0.2"); conn.connect(); Indexer.log.info("url for extracting names:" + conn.getURL()); byte[] b = Util.getBytesFromStream(conn.getInputStream()); String text = new String(b, "UTF-8"); text = Util.unescapeHTML(text); org.jsoup.nodes.Document doc = Jsoup.parse(text); text = doc.body().text(); return namesFromText(text, removeCommonNames); }