List of usage examples for java.net HttpURLConnection connect
public abstract void connect() throws IOException;
From source file:BihuHttpUtil.java
/** * ??HTTPJSON?/*ww w . ja v a2 s . c om*/ * @param url * @param jsonStr */ public static String sendPostForJson(String url, String jsonStr) { StringBuffer sb = new StringBuffer(""); try { // URL realUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); connection.connect(); //POST DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(jsonStr.getBytes("UTF-8"));//??? out.flush(); out.close(); //?? BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String lines; while ((lines = reader.readLine()) != null) { lines = new String(lines.getBytes(), "utf-8"); sb.append(lines); } reader.close(); // connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } return sb.toString(); }
From source file:de.schildbach.wallet.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> requestExchangeRates(final URL url, final String userAgent, final String source, final String... fields) { final long start = System.currentTimeMillis(); HttpURLConnection connection = null; Reader reader = null;//from w w w. j a v 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, Charsets.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 rateStr = o.optString(field, null); if (rateStr != null) { try { final Fiat rate = Fiat.parseFiat(currencyCode, rateStr); if (rate.signum() > 0) { rates.put(currencyCode, new ExchangeRate( new org.bitcoinj.utils.ExchangeRate(rate), source)); break; } } catch (final NumberFormatException 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 exchange rates from {}", 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:com.screenslicer.core.util.Email.java
public static void sendResults(EmailExport export) { if (WebApp.DEV) { return;/*from w w w. j av a 2s. c o m*/ } Map<String, Object> params = new HashMap<String, Object>(); params.put("key", Config.instance.mandrillKey()); List<Map<String, String>> to = new ArrayList<Map<String, String>>(); for (int i = 0; i < export.recipients.length; i++) { to.add(CommonUtil.asMap("email", "name", "type", export.recipients[i], export.recipients[i].split("@")[0], "to")); } List<Map<String, String>> attachments = new ArrayList<Map<String, String>>(); for (Map.Entry<String, byte[]> entry : export.attachments.entrySet()) { attachments.add(CommonUtil.asMap("type", "name", "content", new Tika().detect(entry.getValue()), entry.getKey(), Base64.encodeBase64String(entry.getValue()))); } params.put("message", CommonUtil.asObjMap("track_clicks", "track_opens", "html", "text", "headers", "subject", "from_email", "from_name", "to", "attachments", false, false, "Results attached.", "Results attached.", CommonUtil.asMap("Reply-To", Config.instance.mandrillEmail()), export.title, Config.instance.mandrillEmail(), Config.instance.mandrillEmail(), to, attachments)); params.put("async", true); HttpURLConnection conn = null; String resp = null; Log.info("Sending email: " + export.title, false); try { conn = (HttpURLConnection) new URL("https://mandrillapp.com/api/1.0/messages/send.json") .openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("User-Agent", "Mandrill-Curl/1.0"); String data = CommonUtil.gson.toJson(params, CommonUtil.objectType); byte[] bytes = data.getBytes("utf-8"); conn.setRequestProperty("Content-Length", "" + bytes.length); OutputStream os = conn.getOutputStream(); os.write(bytes); conn.connect(); resp = IOUtils.toString(conn.getInputStream(), "utf-8"); if (resp.contains("\"rejected\"") || resp.contains("\"invalid\"")) { Log.warn("Invalid/rejected email addreses"); } } catch (Exception e) { Log.exception(e); } }
From source file:com.vaguehope.onosendai.util.HttpHelper.java
private static <R> R fetchWithFollowRedirects(final Method method, final URL url, final HttpStreamHandler<R> streamHandler, final int redirectCount) throws IOException, URISyntaxException { final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); try {//from w w w . j a v a 2 s. c om connection.setRequestMethod(method.toString()); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(HTTP_CONNECT_TIMEOUT_SECONDS)); connection.setReadTimeout((int) TimeUnit.SECONDS.toMillis(HTTP_READ_TIMEOUT_SECONDS)); connection.setRequestProperty("User-Agent", "curl/1"); // Make it really clear this is not a browser. //connection.setRequestProperty("Accept-Encoding", "identity"); This fixes missing Content-Length headers but feels wrong. connection.connect(); InputStream is = null; try { final int responseCode = connection.getResponseCode(); // For some reason some devices do not follow redirects. :( if (responseCode == 301 || responseCode == 302 || responseCode == 303 || responseCode == 307) { // NOSONAR not magic numbers. Its HTTP spec. if (redirectCount >= MAX_REDIRECTS) throw new TooManyRedirectsException(responseCode, url, MAX_REDIRECTS); final String locationHeader = connection.getHeaderField("Location"); if (locationHeader == null) throw new HttpResponseException(responseCode, "Location header missing. Headers present: " + connection.getHeaderFields() + "."); connection.disconnect(); final URL locationUrl; if (locationHeader.toLowerCase(Locale.ENGLISH).startsWith("http")) { locationUrl = new URL(locationHeader); } else { locationUrl = url.toURI().resolve(locationHeader).toURL(); } return fetchWithFollowRedirects(method, locationUrl, streamHandler, redirectCount + 1); } if (responseCode < 200 || responseCode >= 300) { // NOSONAR not magic numbers. Its HTTP spec. throw new NotOkResponseException(responseCode, connection, url); } is = connection.getInputStream(); final int contentLength = connection.getContentLength(); if (contentLength < 1) LOG.w("Content-Length=%s for %s.", contentLength, url); return streamHandler.handleStream(connection, is, contentLength); } finally { IoHelper.closeQuietly(is); } } finally { connection.disconnect(); } }
From source file:eu.geopaparazzi.library.network.NetworkUtilities.java
/** * Sends an HTTP GET request to a url//w ww. j a va2 s . co m * * @param urlStr - The URL of the server. (Example: " http://www.yahoo.com/search") * @param file the output file. If it is a folder, it tries to get the file name from the header. * @param requestParameters - all the request parameters (Example: "param1=val1¶m2=val2"). * Note: This method will add the question mark (?) to the request - * DO NOT add it yourself * @param user * @param password * @return the file written. * @throws Exception */ public static File sendGetRequest4File(String urlStr, File file, String requestParameters, String user, String password) throws Exception { if (requestParameters != null && requestParameters.length() > 0) { urlStr += "?" + requestParameters; } HttpURLConnection conn = makeNewConnection(urlStr); conn.setRequestMethod("GET"); // 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(); if (file.isDirectory()) { // try to get the header String headerField = conn.getHeaderField("Content-Disposition"); String fileName = null; if (headerField != null) { String[] split = headerField.split(";"); for (String string : split) { String pattern = "filename="; if (string.toLowerCase().startsWith(pattern)) { fileName = string.replaceFirst(pattern, ""); break; } } } if (fileName == null) { // give a name fileName = "FILE_" + LibraryConstants.TIMESTAMPFORMATTER.format(new Date()); } file = new File(file, fileName); } InputStream in = null; FileOutputStream out = null; try { in = conn.getInputStream(); out = new FileOutputStream(file); byte[] buffer = new byte[(int) maxBufferSize]; int bytesRead = in.read(buffer, 0, (int) maxBufferSize); while (bytesRead > 0) { out.write(buffer, 0, bytesRead); bytesRead = in.read(buffer, 0, (int) maxBufferSize); } out.flush(); } finally { if (in != null) in.close(); if (out != null) out.close(); } return file; }
From source file:net.drgnome.virtualpack.util.Util.java
public static boolean hasUpdate(int projectID, String version) { try {/*w ww. j av a 2s . c o m*/ HttpURLConnection con = (HttpURLConnection) (new URL( "https://api.curseforge.com/servermods/files?projectIds=" + projectID)).openConnection(); con.setConnectTimeout(5000); con.setRequestMethod("GET"); con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; JVM)"); con.setRequestProperty("Pragma", "no-cache"); con.connect(); JSONArray json = (JSONArray) JSONValue.parse(new InputStreamReader(con.getInputStream())); String[] cdigits = ((String) ((JSONObject) json.get(json.size() - 1)).get("name")).toLowerCase() .split("\\."); String[] vdigits = version.toLowerCase().split("\\."); int max = vdigits.length > cdigits.length ? cdigits.length : vdigits.length; int a; int b; for (int i = 0; i < max; i++) { a = b = 0; try { a = Integer.parseInt(cdigits[i]); } catch (Exception e1) { char[] c = cdigits[i].toCharArray(); for (int j = 0; j < c.length; j++) { a += (c[j] << ((c.length - (j + 1)) * 8)); } } try { b = Integer.parseInt(vdigits[i]); } catch (Exception e1) { char[] c = vdigits[i].toCharArray(); for (int j = 0; j < c.length; j++) { b += (c[j] << ((c.length - (j + 1)) * 8)); } } if (a > b) { return true; } else if (a < b) { return false; } else if ((i == max - 1) && (cdigits.length > vdigits.length)) { return true; } } } catch (Exception e) { } return false; }
From source file:edu.stanford.muse.launcher.Splash.java
private static boolean killRunningServer(String url) throws IOException { try {//ww w .j a va 2 s . 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 err.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:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java
public static HttpResponse doGet(String endpoint, Map<String, String> headers) throws IOException { HttpResponse httpResponse;//from w ww.j ava 2 s . co m if (endpoint.startsWith("http://")) { URL url = new URL(endpoint); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoOutput(true); conn.setReadTimeout(30000); // setting headers if (headers != null && headers.size() > 0) { Iterator<String> itr = headers.keySet().iterator(); while (itr.hasNext()) { String key = itr.next(); conn.setRequestProperty(key, headers.get(key)); } } conn.connect(); // Get the response StringBuilder sb = new StringBuilder(); BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } httpResponse = new HttpResponse(sb.toString(), conn.getResponseCode()); httpResponse.setResponseMessage(conn.getResponseMessage()); } catch (IOException ignored) { rd = new BufferedReader(new InputStreamReader(conn.getErrorStream())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } httpResponse = new HttpResponse(sb.toString(), conn.getResponseCode()); httpResponse.setResponseMessage(conn.getResponseMessage()); } finally { if (rd != null) { rd.close(); } } return httpResponse; } return null; }
From source file:com.cannabiscoin.wallet.ExchangeRatesProvider.java
private static Object getCoinValueBTC_BTER() { Date date = new Date(); long now = date.getTime(); //final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); // Keep the LTC rate around for a bit Double btcRate = 0.0;// ww w .j a v a 2 s . c o m String currency = CoinDefinition.cryptsyMarketCurrency; String url = "https://bittrex.com/api/v1.1/public/getticker?market=BTC-CANN"; HttpURLConnection connection = null; try { // final String currencyCode = currencies[i]; final URL URL_bter = new URL(url); connection = (HttpURLConnection) URL_bter.openConnection(); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS * 2); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS * 2); connection.connect(); final StringBuilder content = new StringBuilder(); Reader reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024)); Io.copy(reader, content); final JSONObject head = new JSONObject(content.toString()); String result = head.getString("result"); if (result.equals("true")) { Double averageTrade = head.getDouble("Bid"); if (currency.equalsIgnoreCase("BTC")) btcRate = averageTrade; } } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } } return btcRate; } catch (final IOException x) { x.printStackTrace(); } catch (final JSONException x) { x.printStackTrace(); } finally { if (connection != null) connection.disconnect(); } return null; }
From source file:com.example.android.ennis.barrett.popularmovies.asynchronous.TMDbSyncUtil.java
private static String fetch(Uri uri) { HttpURLConnection connection = null; BufferedReader reader = null; String rawJSON = ""; Log.d(TAG, uri.toString());//from w ww. j a v a 2s .com try { URL url = new URL(uri.toString()); //java.net Malformed uri exception connection = (HttpURLConnection) url.openConnection(); //java.io. IO exception connection.setRequestMethod("GET"); //java.net.ProtocolException && unnecessary connection.connect(); //java.io.IOExecption InputStream inputStream = connection.getInputStream(); // java.io.IOException StringBuffer stringBuffer = new StringBuffer(); if (inputStream == null) { return rawJSON; } reader = new BufferedReader(new InputStreamReader(inputStream)); //Make the string more readable String line; while ((line = reader.readLine()) != null) { stringBuffer.append(line + "\n"); } rawJSON = stringBuffer.toString(); Log.d(TAG + "doInBackground", rawJSON); } catch (IOException e) { Log.e(TAG, "Error ", e); e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(TAG, "Error closing stream", e); } } } return rawJSON; }