Example usage for java.net HttpURLConnection connect

List of usage examples for java.net HttpURLConnection connect

Introduction

In this page you can find the example usage for java.net HttpURLConnection connect.

Prototype

public abstract void connect() throws IOException;

Source Link

Document

Opens a communications link to the resource referenced by this URL, if such a connection has not already been established.

Usage

From source file:com.eryansky.common.web.servlet.RemoteContentServlet.java

private void fetchContentByJDKConnection(HttpServletResponse response, String contentUrl) throws IOException {

    HttpURLConnection connection = (HttpURLConnection) new URL(contentUrl).openConnection();
    // Socket//from w w  w.j ava 2s  . co  m
    connection.setReadTimeout(TIMEOUT_SECONDS * 1000);
    try {
        connection.connect();

        // ?
        InputStream input;
        try {
            input = connection.getInputStream();
        } catch (FileNotFoundException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, contentUrl + " is not found.");
            return;
        }

        // Header
        response.setContentType(connection.getContentType());
        if (connection.getContentLength() > 0) {
            response.setContentLength(connection.getContentLength());
        }

        // 
        OutputStream output = response.getOutputStream();
        try {
            // byte?InputStreamOutputStream, ?4k.
            IOUtils.copy(input, output);
            output.flush();
        } finally {
            // ??InputStream.
            IOUtils.closeQuietly(input);
        }
    } finally {
        connection.disconnect();
    }
}

From source file:br.bireme.accounts.Authentication.java

public JSONObject getUser(final String user, final String password) throws IOException, ParseException {
    if (user == null) {
        throw new NullPointerException("user");
    }/*w  w  w. j av  a  2 s .  c om*/
    if (password == null) {
        throw new NullPointerException("password");
    }

    final JSONObject parameters = new JSONObject();
    parameters.put("username", user);
    parameters.put("password", password);
    parameters.put("service", SERVICE_NAME);
    parameters.put("format", "json");

    //final URL url = new URL("http", host, port, DEFAULT_PATH);
    final URL url = new URL("http://" + host + DEFAULT_PATH);
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.connect();

    final StringBuilder builder = new StringBuilder();
    final BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));

    //final String message = parameters.toJSONString();
    //System.out.println(message);

    writer.write(parameters.toJSONString());
    writer.newLine();
    writer.close();

    final int respCode = connection.getResponseCode();
    final boolean respCodeOk = (respCode == 200);
    final BufferedReader reader;

    if (respCodeOk) {
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    } else {
        reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
    }

    while (true) {
        final String line = reader.readLine();
        if (line == null) {
            break;
        }
        builder.append(line);
        builder.append("\n");
    }

    reader.close();

    if (!respCodeOk && (respCode != 401)) {
        throw new IOException(builder.toString());
    }

    return (JSONObject) new JSONParser().parse(builder.toString());
}

From source file:com.cloudbees.mtslaves.client.RemoteReference.java

protected HttpURLConnection postJson(HttpURLConnection con, JSONObject json) throws IOException {
    try {//from  w w  w.  j  a  v a  2  s . co m
        token.authorizeRequest(con);
        con.setDoOutput(true);
        con.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
        con.connect();

        // send JSON
        OutputStreamWriter w = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
        json.write(w);
        w.close();

        return con;
    } catch (IOException e) {
        throw (IOException) new IOException("Failed to POST to " + url).initCause(e);
    }
}

From source file:io.indy.drone.service.ScheduledService.java

private String httpGet(String path) throws IOException {
    BufferedReader reader = null;
    try {// w  w w  .ja v  a 2 s  .  com
        URL url = new URL(path);
        HttpURLConnection c = (HttpURLConnection) url.openConnection();

        c.setRequestMethod("GET");
        c.setReadTimeout(15000);
        c.connect();

        reader = new BufferedReader(new InputStreamReader(c.getInputStream()));
        StringBuilder buf = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            buf.append(line + "\n");
        }

        return buf.toString();

    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:com.acrutiapps.browser.tasks.SearchUrlTask.java

@Override
protected String doInBackground(Void... params) {

    publishProgress(0);//from  w ww.j a v  a 2  s.  co m

    String message = null;
    HttpURLConnection c = null;

    try {
        URL url = new URL("http://anasthase.github.com/TintBrowser/search-engines.json");
        c = (HttpURLConnection) url.openConnection();

        c.connect();

        int responseCode = c.getResponseCode();

        if (responseCode == 200) {
            StringBuilder sb = new StringBuilder();

            InputStream is = c.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));

            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            publishProgress(1);

            JSONArray jsonArray = new JSONArray(sb.toString());

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);

                String groupName = jsonObject.getString("group");

                SearchUrlGroup group = mResults.get(groupName);
                if (group == null) {
                    group = new SearchUrlGroup(groupName);
                    mResults.put(groupName, group);
                }

                JSONArray items = jsonObject.getJSONArray("items");
                for (int j = 0; j < items.length(); j++) {
                    JSONObject item = items.getJSONObject(j);

                    group.addItem(item.getString("name"), item.getString("url"));
                }
            }

        } else {
            message = String.format(mContext.getString(R.string.SearchUrlBadResponseCodeMessage),
                    Integer.toString(responseCode));
        }

    } catch (MalformedURLException e) {
        message = e.getMessage();
    } catch (IOException e) {
        message = e.getMessage();
    } catch (JSONException e) {
        message = e.getMessage();
    } finally {
        if (c != null) {
            c.disconnect();
        }
    }

    return message;
}

From source file:ai.api.RequestTask.java

@Override
protected String doInBackground(final String... params) {
    final String payload = params[0];
    if (TextUtils.isEmpty(payload)) {
        throw new IllegalArgumentException("payload argument should not be empty");
    }/*ww w .  j  av  a2  s  .  co m*/

    String response = null;
    HttpURLConnection connection = null;

    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);

        connection.connect();

        final BufferedOutputStream outputStream = new BufferedOutputStream(connection.getOutputStream());
        IOUtils.write(payload, outputStream, Charsets.UTF_8);
        outputStream.close();

        final InputStream inputStream = new BufferedInputStream(connection.getInputStream());
        response = IOUtils.toString(inputStream, Charsets.UTF_8);
        inputStream.close();

        return response;

    } catch (final IOException e) {
        Log.e(TAG,
                "Can't make request to the Speaktoit AI service. Please, check connection settings and API access token.",
                e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }

    return null;
}

From source file:com.predic8.membrane.core.interceptor.balancer.NodeOnlineChecker.java

private List<BadNode> pingOfflineNodes() {
    ArrayList<BadNode> onlineNodes = new ArrayList<BadNode>();

    for (BadNode node : offlineNodes) {
        URL url = null;//ww w .  ja  v  a 2  s. c o  m
        try {
            url = new URL(node.getNode().getHost());
        } catch (MalformedURLException ignored) {
            continue;
        }
        try {
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            urlConn.setConnectTimeout(pingTimeoutInSeconds * 1000);
            urlConn.connect();
            if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK)
                onlineNodes.add(node);
        } catch (IOException ignored) {
            continue;
        }
    }

    return onlineNodes;
}

From source file:com.googlecode.jsonrpc4j.JsonRpcHttpClient.java

/**
 * Invokes the given method with the given arguments and returns
 * an object of the given type, or null if void.
 *
 * @see JsonRpcClient#writeRequest(String, Object, java.io.OutputStream, String)
 * @param methodName the name of the method to invoke
 * @param arguments the arguments to the method
 * @param returnType the return type/*from   ww w. ja  va2s. c om*/
 * @param extraHeaders extra headers to add to the request
 * @return the return value
 * @throws Throwable on error
 */
public Object invoke(String methodName, Object argument, Type returnType, Map<String, String> extraHeaders)
        throws Throwable {

    // create URLConnection
    HttpURLConnection con = prepareConnection(extraHeaders);
    con.connect();

    // invoke it
    OutputStream ops = con.getOutputStream();
    try {
        super.invoke(methodName, argument, ops);
    } finally {
        ops.close();
    }

    // read and return value
    try {
        InputStream ips = con.getInputStream();
        try {
            // in case of http error try to read response body and return it in exception
            return super.readResponse(returnType, ips);
        } finally {
            ips.close();
        }
    } catch (IOException e) {
        throw new HttpException(readString(con.getErrorStream()), e);
    }
}

From source file:com.cannabiscoin.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, final String userAgent,
        final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;/* w  w  w.j  a  v a2  s .  c  om*/

    try {

        Double btcRate = 0.0;
        boolean cryptsyValue = true;
        Object result = getCoinValueBTC();

        if (result == null) {
            result = getCoinValueBTC_BTER();
            cryptsyValue = false;
            if (result == null)
                return null;
        }
        btcRate = (Double) result;

        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.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) {
                        String rateStr = o.optString(field, null);

                        if (rateStr != null) {
                            try {
                                double rateForBTC = Double.parseDouble(rateStr);

                                rateStr = String.format("%.8f", rateForBTC * btcRate).replace(",", ".");

                                final BigInteger rate = GenericUtils.toNanoCoins(rateStr, 0);

                                if (rate.signum() > 0) {
                                    rates.put(currencyCode,
                                            new ExchangeRate(currencyCode, rate, 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));

            //Add Bitcoin information
            if (rates.size() == 0) {
                int i = 0;
                i++;
            } else {
                rates.put(CoinDefinition.cryptsyMarketCurrency,
                        new ExchangeRate(CoinDefinition.cryptsyMarketCurrency,
                                GenericUtils.toNanoCoins(String.format("%.8f", btcRate).replace(",", "."), 0),
                                cryptsyValue ? "pubapi.cryptsy.com" : "data.bter.com"));
                rates.put("m" + CoinDefinition.cryptsyMarketCurrency,
                        new ExchangeRate("m" + CoinDefinition.cryptsyMarketCurrency,
                                GenericUtils.toNanoCoins(
                                        String.format("%.5f", btcRate * 1000).replace(",", "."), 0),
                                cryptsyValue ? "pubapi.cryptsy.com" : "data.bter.com"));
            }

            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:ms.sujinkim.com.test.api.FoscamSnapshotRunnable.java

public void run() {
    ToastManager manager = ToastManager.getInstance();
    HttpURLConnection conn = null;
    String urlString = FoscamUrlFactory.getSnapshotUrl(camera);
    //DefaultHttpClient client = new DefaultHttpClient();
    try {//from   ww w  .j  a  v a  2s .  c  om
        URL url = new URL(urlString);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.connect();
        int status = conn.getResponseCode();
        if (status != 200) {
            manager.makeToast("Unable to take snapshot: " + status);
            conn.disconnect();
            return;
        }

        String name = conn.getHeaderField(CONTENT_DISPOSITION);// ? name?  ?.
        InputStream inputStream = conn.getInputStream();
        if (inputStream != null) {
            writeSnapshot(name, inputStream);
            manager.makeToast("Saved \"" + name + "\"");
        }
    } catch (Exception e) {
        ToastManager.getInstance().makeToast("Unable to take snapshot: " + e.getMessage());
    } finally {
        conn.disconnect();
    }
}