List of usage examples for java.net HttpURLConnection connect
public abstract void connect() throws IOException;
From source file:com.gmt2001.HttpRequest.java
public static HttpResponse getData(RequestType type, String url, String post, HashMap<String, String> headers) { Thread.setDefaultUncaughtExceptionHandler(com.gmt2001.UncaughtExceptionHandler.instance()); HttpResponse r = new HttpResponse(); r.type = type;/*from ww w .j ava2s .com*/ r.url = url; r.post = post; r.headers = headers; try { URL u = new URL(url); HttpURLConnection h = (HttpURLConnection) u.openConnection(); for (Entry<String, String> e : headers.entrySet()) { h.addRequestProperty(e.getKey(), e.getValue()); } h.setRequestMethod(type.name()); h.setUseCaches(false); h.setDefaultUseCaches(false); h.setConnectTimeout(timeout); h.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015"); if (!post.isEmpty()) { h.setDoOutput(true); } h.connect(); if (!post.isEmpty()) { BufferedOutputStream stream = new BufferedOutputStream(h.getOutputStream()); stream.write(post.getBytes()); stream.flush(); stream.close(); } if (h.getResponseCode() < 400) { r.content = IOUtils.toString(new BufferedInputStream(h.getInputStream()), h.getContentEncoding()); r.httpCode = h.getResponseCode(); r.success = true; } else { r.content = IOUtils.toString(new BufferedInputStream(h.getErrorStream()), h.getContentEncoding()); r.httpCode = h.getResponseCode(); r.success = false; } } catch (IOException ex) { r.success = false; r.httpCode = 0; r.exception = ex.getMessage(); com.gmt2001.Console.err.printStackTrace(ex); } return r; }
From source file:org.grameenfoundation.consulteca.utils.HttpHelpers.java
public static InputStream getResource(String imageUrl) throws IOException { HttpURLConnection httpUrlConnection = null; URL url = new URL(imageUrl); httpUrlConnection = (HttpURLConnection) url.openConnection(); HttpHelpers.addCommonHeaders(httpUrlConnection); httpUrlConnection.setConnectTimeout(NETWORK_TIMEOUT); httpUrlConnection.setReadTimeout(NETWORK_TIMEOUT); httpUrlConnection.connect(); return getInputStream(httpUrlConnection); }
From source file:dlauncher.authorization.DefaultCredentialsManager.java
private static JSONObject makeRequest(URL url, JSONObject post, boolean ignoreErrors) throws ProtocolException, IOException, AuthorizationException { JSONObject obj = null;//from w ww. ja va 2 s. c om try { HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json"); con.setConnectTimeout(15 * 1000); con.setReadTimeout(15 * 1000); con.connect(); try (OutputStream out = con.getOutputStream()) { out.write(post.toString().getBytes(Charset.forName("UTF-8"))); } con.getResponseCode(); InputStream instr; instr = con.getErrorStream(); if (instr == null) { instr = con.getInputStream(); } byte[] data = new byte[1024]; int length; try (SizeLimitedByteArrayOutputStream bytes = new SizeLimitedByteArrayOutputStream(1024 * 4)) { try (InputStream in = new BufferedInputStream(instr)) { while ((length = in.read(data)) >= 0) { bytes.write(data, 0, length); } } byte[] rawBytes = bytes.toByteArray(); if (rawBytes.length != 0) { obj = new JSONObject(new String(rawBytes, Charset.forName("UTF-8"))); } else { obj = new JSONObject(); } if (!ignoreErrors && obj.has("error")) { String error = obj.getString("error"); String errorMessage = obj.getString("errorMessage"); String cause = obj.optString("cause", null); if ("ForbiddenOperationException".equals(error)) { if ("UserMigratedException".equals(cause)) { throw new UserMigratedException(errorMessage); } throw new ForbiddenOperationException(errorMessage); } throw new AuthorizationException( error + (cause != null ? "." + cause : "") + ": " + errorMessage); } return obj; } } catch (JSONException ex) { throw new InvalidResponseException(ex, obj); } }
From source file:Main.java
public static String getPosthtml(String posturl, String postData, String encode) { String html = ""; URL url;//from w w w . ja v a 2s . c o m try { url = new URL(posturl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("User-Agent", userAgent); String postDataStr = postData; byte[] bytes = postDataStr.getBytes("utf-8"); connection.setRequestProperty("Content-Length", "" + bytes.length); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Cache-Control", "no-cache"); connection.setDoOutput(true); connection.setReadTimeout(timeout); connection.setFollowRedirects(true); connection.connect(); OutputStream outStrm = connection.getOutputStream(); outStrm.write(bytes); outStrm.flush(); outStrm.close(); InputStream inStrm = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inStrm, encode)); String temp = ""; while ((temp = br.readLine()) != null) { html += (temp + '\n'); } br.close(); connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } return html; }
From source file:com.dopecoin.wallet.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> requestExchangeRates(final URL url, float leafBtcConversion, final String userAgent, final String... fields) { final long start = System.currentTimeMillis(); HttpURLConnection connection = null; Reader reader = null;// ww w. j a va 2 s . c o m try { connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.addRequestProperty("User-Agent", userAgent); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { 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>(); 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 leafRate = btcRate.multiply(BigDecimal.valueOf(leafBtcConversion)) .toBigInteger(); if (leafRate.signum() > 0) { rates.put(currencyCode, new ExchangeRate(currencyCode, leafRate, url.getHost())); break; } } catch (final ArithmeticException x) { log.warn("problem fetching {} exchange rate from {}: {}", new Object[] { currencyCode, url, x.getMessage() }); } } } } } log.info("fetched exchange rates from {}, took {} ms", url, (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:org.voota.api.VootaApi.java
/** * Loads image data by url and returns byte array filled by this data. If * method fails to load image, it will return null. * * @param urlImage url represents image to load * @return byte array filled by image data or null if image * loading fails *//*from w w w. ja v a2s. c om*/ static public byte[] getUrlImageBytes(URL urlImage) { byte[] bytesImage = null; try { HttpURLConnection conn = (HttpURLConnection) urlImage.openConnection(); conn.setDoInput(true); conn.connect(); InputStream is = conn.getInputStream(); int bytesAvavilable = conn.getContentLength(); bytesImage = new byte[bytesAvavilable]; int nReaded = 0, nSum = 0; while (bytesAvavilable > nSum) { nReaded = is.read(bytesImage, nSum, bytesAvavilable - nSum); nSum += nReaded; } } catch (IOException e) { } return bytesImage; }
From source file:org.voota.api.VootaApi.java
/** * Loads image data by url and returns byte array filled by this data. If * method fails to load image, it will return null. This method takes url as * String object and converts file name to used character set, because it * may contain Spanish symbols. //w w w .ja v a 2s. c o m * * @param urlImage url in String object represents image to load * @return byte array filled by image data or null if image * loading fails */ static public byte[] getUrlImageBytes(String strUrlImage) { byte[] bytesImage = null; try { URL urlImage = new URL(getEncodedImageUrl(strUrlImage)); HttpURLConnection conn = (HttpURLConnection) urlImage.openConnection(); conn.setDoInput(true); conn.connect(); InputStream is = conn.getInputStream(); int bytesAvavilable = conn.getContentLength(); bytesImage = new byte[bytesAvavilable]; int nReaded = 0, nSum = 0; while (bytesAvavilable > nSum) { nReaded = is.read(bytesImage, nSum, bytesAvavilable - nSum); nSum += nReaded; } } catch (IOException e) { } return bytesImage; }
From source file:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java
/** * Create a new dataset/*from ww w . ja v a 2 s .c o m*/ * * @param dataSetName * @throws IOException * @throws HttpException */ public static void createDataSet(@NonNull String dataSetName) throws IOException, HttpException { logger.info("create dataset: " + dataSetName); URL url = new URL(HOST + "/$/datasets"); final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.setUseCaches(false); httpConnection.setRequestMethod("POST"); httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // set content httpConnection.setDoOutput(true); final OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream()); out.write("dbName=" + URLEncoder.encode(dataSetName, "UTF-8") + "&dbType=mem"); out.close(); // handle HTTP/HTTPS strange behaviour httpConnection.connect(); httpConnection.disconnect(); // handle response switch (httpConnection.getResponseCode()) { case HttpURLConnection.HTTP_OK: break; default: throw new HttpException( httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage()); } }
From source file:com.cyphermessenger.client.SyncRequest.java
public static HttpURLConnection doRequest(String endpoint, CypherSession session, String[] keys, String[] values) throws IOException { HttpURLConnection connection = (java.net.HttpURLConnection) new URL(DOMAIN + endpoint).openConnection(); connection.setDoOutput(true);/* w w w . j a va2 s . co m*/ connection.setRequestMethod("POST"); connection.setRequestProperty("Accept-Charset", "UTF-8"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); connection.connect(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream())); if (session != null) { writer.write("userID="); writer.write(session.getUser().getUserID() + "&sessionID="); writer.write(session.getSessionID()); } if (keys != null && keys.length > 0) { if (session != null) { writer.write('&'); } // write first row writer.write(keys[0]); writer.write('='); writer.write(URLEncoder.encode(values[0], "UTF-8")); for (int i = 1; i < keys.length; i++) { writer.write('&'); writer.write(keys[i]); writer.write('='); writer.write(URLEncoder.encode(values[i], "UTF-8")); } } writer.close(); return connection; }
From source file:ja.ohac.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 ww . j a v a 2s.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 BigInteger rate = GenericUtils.parseCoin(rateStr, 0); if (rate.signum() > 0) { rates.put(currencyCode, new ExchangeRate(currencyCode, rate, 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 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; }