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.nit.vicky.web.HttpFetcher.java

public static String downloadFileToSdCardMethod(String UrlToFile, Context context, String prefix, String method,
        Boolean isMP3) {/*from w  ww  .  j  a va 2 s.  co  m*/
    try {
        URL url = new URL(UrlToFile);

        String extension = ".mp3";

        if (!isMP3)
            extension = UrlToFile.substring(UrlToFile.lastIndexOf("."));

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(10 * 1000);
        urlConnection.setReadTimeout(10 * 1000);
        urlConnection.setRequestMethod(method);
        //urlConnection.setRequestProperty("Referer", "http://mm.taobao.com/");
        urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
        urlConnection.setRequestProperty("Accept", "*/*");
        urlConnection.connect();

        File file = File.createTempFile(prefix, extension, DiskUtil.getStoringDirectory());

        FileOutputStream fileOutput = new FileOutputStream(file);
        InputStream inputStream = urlConnection.getInputStream();

        byte[] buffer = new byte[1024];
        int bufferLength = 0;

        while ((bufferLength = inputStream.read(buffer)) > 0) {
            fileOutput.write(buffer, 0, bufferLength);
        }
        fileOutput.close();

        return file.getAbsolutePath();

    } catch (Exception e) {
        return "FAILED " + e.getMessage();
    }
}

From source file:hashengineering.digitalcoin.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getBitcoinCharts() {
    try {//  w ww . j av  a 2  s. c o  m
        Double btcRate = 0.0;

        Object result = getCoinValueBTC();

        if (result == null)
            return null;

        else
            btcRate = (Double) result;

        final URL URL = new URL("http://api.bitcoincharts.com/v1/weighted_prices.json");
        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();
                if (!"timestamp".equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);
                    String rate = o.optString("24h", null);
                    if (rate == null)
                        rate = o.optString("7d", null);
                    if (rate == null)
                        rate = o.optString("30d", null);

                    double rateForBTC = Double.parseDouble(rate);

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

                    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:de.mas.telegramircbot.utils.images.ImgurUploader.java

public static String uploadImageAndGetLink(String clientID, byte[] image) throws IOException {
    URL url;//w  w  w.  j  a va 2  s.  c  o m
    url = new URL(Settings.IMGUR_API_URL);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    String dataImage = Base64.getEncoder().encodeToString(image);
    String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(dataImage, "UTF-8");

    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization", "Client-ID " + clientID);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    conn.connect();
    StringBuilder stb = new StringBuilder();
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        stb.append(line).append("\n");
    }
    wr.close();
    rd.close();

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(ImgurResponse.class, new ImgurResponseDeserializer());
    Gson gson = gsonBuilder.create();

    // The JSON data
    try {
        ImgurResponse response = gson.fromJson(stb.toString(), ImgurResponse.class);
        return response.getLink();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return stb.toString();
}

From source file:fr.zcraft.zbanque.network.PacketSender.java

private static HTTPResponse makeRequest(String url, PacketPlayOut.PacketType method, String data)
        throws Throwable {
    // ***  REQUEST  ***

    final URL urlObj = new URL(url);
    final HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();

    connection.setRequestMethod(method.name());
    connection.setRequestProperty("User-Agent", USER_AGENT);

    authenticateRequest(connection);//from w  w w . j a v a2 s  .  c  o m

    connection.setDoOutput(true);

    try {
        try {
            connection.connect();
        } catch (IOException ignored) {
        }

        if (method == PacketPlayOut.PacketType.POST) {
            DataOutputStream out = null;
            try {
                out = new DataOutputStream(connection.getOutputStream());
                if (data != null)
                    out.writeBytes(data);
                out.flush();
            } finally {
                if (out != null)
                    out.close();
            }
        }

        // ***  RESPONSE  ***

        int responseCode;
        boolean failed = false;

        try {
            responseCode = connection.getResponseCode();
        } catch (IOException e) {
            // HttpUrlConnection will throw an IOException if any 4XX
            // response is sent. If we request the status again, this
            // time the internal status will be properly set, and we'll be
            // able to retrieve it.
            // Thanks to Iigo.
            responseCode = connection.getResponseCode();
            failed = true;
        }

        BufferedReader in = null;
        String body = "";
        try {
            InputStream stream;
            try {
                stream = connection.getInputStream();
            } catch (IOException e) {
                // Same as before
                stream = connection.getErrorStream();
                failed = true;
            }

            in = new BufferedReader(new InputStreamReader(stream));
            StringBuilder responseBuilder = new StringBuilder();

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                responseBuilder.append(inputLine);
            }

            body = responseBuilder.toString();
        } finally {
            if (in != null)
                in.close();
        }

        HTTPResponse response = new HTTPResponse();
        response.setResponseCode(responseCode, failed);
        response.setResponseBody(body);

        int i = 0;
        String headerName, headerContent;
        while ((headerName = connection.getHeaderFieldKey(i)) != null) {
            headerContent = connection.getHeaderField(i);
            response.addHeader(headerName, headerContent);
        }

        // ***  REDIRECTION  ***

        switch (responseCode) {
        case 301:
        case 302:
        case 307:
        case 308:
            if (response.getHeaders().containsKey("Location")) {
                response = makeRequest(response.getHeaders().get("Location"), method, data);
            }
        }

        // ***  END  ***

        return response;
    } finally {
        connection.disconnect();
    }
}

From source file:Main.java

/**
 * Do an HTTP POST and return the data as a byte array.
 *//* w ww.  j a va  2  s  .  co m*/
public static byte[] executePost(String url, byte[] data, Map<String, String> requestProperties)
        throws MalformedURLException, IOException {
    HttpURLConnection urlConnection = null;
    try {
        urlConnection = (HttpURLConnection) new URL(url).openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(data != null);
        urlConnection.setDoInput(true);
        if (requestProperties != null) {
            for (Map.Entry<String, String> requestProperty : requestProperties.entrySet()) {
                urlConnection.setRequestProperty(requestProperty.getKey(), requestProperty.getValue());
            }
        }
        urlConnection.connect();
        if (data != null) {
            OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
            out.write(data);
            out.close();
        }
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        return convertInputStreamToByteArray(in);
    } catch (IOException e) {
        String details;
        if (urlConnection != null) {
            details = "; code=" + urlConnection.getResponseCode() + " (" + urlConnection.getResponseMessage()
                    + ")";
        } else {
            details = "";
        }
        Log.e("ExoplayerUtil", "executePost: Request failed" + details, e);
        throw e;
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:com.webarch.common.net.http.HttpService.java

/**
 * /*from  ww w .  j a  v  a 2  s.  co  m*/
 *
 * @param media_id ?ID
 * @param identity 
 * @param filepath ?(????)
 * @return ?(???)error
 */
public static String downLoadMediaFile(String requestUrl, String media_id, String identity, String filepath) {
    String mediaLocalURL = "error";
    InputStream inputStream = null;
    FileOutputStream fileOutputStream = null;
    DataOutputStream dataOutputStream = null;
    try {
        URL downLoadURL = new URL(requestUrl);
        // URL
        HttpURLConnection connection = (HttpURLConnection) downLoadURL.openConnection();
        //?
        connection.setRequestMethod("GET");
        // 
        connection.connect();
        //?,?text,json
        if (connection.getContentType().equalsIgnoreCase("text/plain")) {
            // BufferedReader???URL?
            inputStream = connection.getInputStream();
            BufferedReader read = new BufferedReader(new InputStreamReader(inputStream, DEFAULT_CHARSET));
            String valueString = null;
            StringBuffer bufferRes = new StringBuffer();
            while ((valueString = read.readLine()) != null) {
                bufferRes.append(valueString);
            }
            inputStream.close();
            String errMsg = bufferRes.toString();
            JSONObject jsonObject = JSONObject.parseObject(errMsg);
            logger.error("???" + (jsonObject.getInteger("errcode")));
            mediaLocalURL = "error";
        } else {
            BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
            String ds = connection.getHeaderField("Content-disposition");
            //??
            String fullName = ds.substring(ds.indexOf("filename=\"") + 10, ds.length() - 1);
            //?--??
            String preffix = fullName.substring(0, fullName.lastIndexOf("."));
            //?
            String suffix = fullName.substring(preffix.length() + 1);
            //
            String length = connection.getHeaderField("Content-Length");
            //
            String type = connection.getHeaderField("Content-Type");
            //
            byte[] buffer = new byte[8192]; // 8k
            int count = 0;
            mediaLocalURL = filepath + File.separator;
            File file = new File(mediaLocalURL);
            if (!file.exists()) {
                file.mkdirs();
            }
            File mediaFile = new File(mediaLocalURL, fullName);
            fileOutputStream = new FileOutputStream(mediaFile);
            dataOutputStream = new DataOutputStream(fileOutputStream);
            while ((count = bis.read(buffer)) != -1) {
                dataOutputStream.write(buffer, 0, count);
            }
            //?
            mediaLocalURL += fullName;
            bis.close();
            dataOutputStream.close();
            fileOutputStream.close();
        }
    } catch (IOException e) {
        logger.error("?", e);
    }
    return mediaLocalURL;
}

From source file:com.mopaas_mobile.http.BaseHttpRequester.java

public static String doPOST(String urlstr, List<BasicNameValuePair> params) throws IOException {
    String result = null;// www  . j  a  v a  2s .c  om
    URL url = new URL(urlstr);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestMethod("POST");
    connection.setUseCaches(false);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    //       connection.setRequestProperty("token",token);
    connection.setConnectTimeout(30000);
    connection.setReadTimeout(30000);
    connection.connect();

    DataOutputStream out = new DataOutputStream(connection.getOutputStream());

    String content = "";
    if (params != null && params.size() > 0) {
        for (int i = 0; i < params.size(); i++) {
            content = content + "&" + URLEncoder.encode(((NameValuePair) params.get(i)).getName(), "UTF-8")
                    + "=" + URLEncoder.encode(((NameValuePair) params.get(i)).getValue(), "UTF-8");
        }
        out.writeBytes(content.substring(1));
    }

    out.flush();
    out.close();
    InputStream is = connection.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

    StringBuffer b = new StringBuffer();
    int ch;
    while ((ch = br.read()) != -1) {
        b.append((char) ch);
    }
    result = b.toString().trim();
    connection.disconnect();
    return result;
}

From source file:LNISmokeTest.java

/**
 * Implement WebDAV PUT http request./*from   w  w w.j ava  2 s .co  m*/
 * 
 * This might be simpler with a real HTTP client library, but
 * java.net.HttpURLConnection is part of the standard SDK and it
 * demonstrates the concepts.
 * 
 * @param lni the lni
 * @param collHandle the coll handle
 * @param packager the packager
 * @param source the source
 * @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 doPut(LNISoapServlet lni, String collHandle, String packager, String source,
        String endpoint)
        throws java.rmi.RemoteException, ProtocolException, IOException, FileNotFoundException {
    // assemble URL from chopped endpoint-URL and relative URI
    String collURI = doLookup(lni, collHandle, null);
    URL url = LNIClientUtils.makeDAVURL(endpoint, collURI, packager);
    System.err.println("DEBUG: PUT file=" + source + " to URL=" + url.toString());

    // connect with PUT method, then copy file over.
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("PUT");
    conn.setDoOutput(true);
    fixBasicAuth(url, conn);
    conn.connect();

    InputStream in = null;
    OutputStream out = null;
    try {
        in = new FileInputStream(source);
        out = conn.getOutputStream();
        copyStream(in, out);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                log.error("Unable to close input stream", e);
            }
        }

        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                log.error("Unable to close output stream", e);
            }
        }
    }

    int status = conn.getResponseCode();
    if (status < 200 || status >= 300) {
        die(status, "HTTP error, status=" + String.valueOf(status) + ", message=" + conn.getResponseMessage());
    }

    // diagnostics, and get resulting new item's location if avail.
    System.err.println("DEBUG: sent " + source);
    System.err.println(
            "RESULT: Status=" + String.valueOf(conn.getResponseCode()) + " " + conn.getResponseMessage());
    String loc = conn.getHeaderField("Location");
    System.err.println("RESULT: Location=" + ((loc == null) ? "NULL!" : loc));
}

From source file:com.magnet.plugin.helpers.URLHelper.java

public static InputStream loadUrl(final String url) throws Exception {
    final InputStream[] inputStreams = new InputStream[] { null };
    final Exception[] exception = new Exception[] { null };
    Future<?> downloadThreadFuture = ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
        public void run() {
            try {
                HttpURLConnection connection;
                if (ApplicationManager.getApplication() != null) {
                    connection = HttpConfigurable.getInstance().openHttpConnection(url);
                } else {
                    connection = (HttpURLConnection) new URL(url).openConnection();
                    connection.setReadTimeout(Rest2MobileConstants.CONNECTION_TIMEOUT);
                    connection.setConnectTimeout(Rest2MobileConstants.CONNECTION_TIMEOUT);
                }/*from   w ww . j  a  v  a 2 s  .  co  m*/
                connection.connect();

                inputStreams[0] = connection.getInputStream();
            } catch (IOException e) {
                exception[0] = e;
            }
        }
    });

    try {
        downloadThreadFuture.get(5, TimeUnit.SECONDS);
    } catch (TimeoutException ignored) {
    }

    if (!downloadThreadFuture.isDone()) {
        downloadThreadFuture.cancel(true);
        throw new ConnectionException(IdeBundle.message("updates.timeout.error"));
    }

    if (exception[0] != null)
        throw exception[0];
    return inputStreams[0];
}

From source file:biz.mosil.webtools.MosilWeb.java

/**
 * ? InputStream//  w w w  .j a  v a  2 s. c  o  m
 * */
public static final InputStream getInputStream(final String _url) {
    InputStream result = null;

    try {
        URL url = new URL(_url);
        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection)) {
            throw new IOException("This URL Can't Connect!");
        }

        HttpURLConnection httpConn = (HttpURLConnection) conn;
        //????
        httpConn.setAllowUserInteraction(false);
        //??
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();

        final int response = httpConn.getResponseCode();

        if (response == HttpURLConnection.HTTP_OK) {
            result = httpConn.getInputStream();
        }

    } catch (MalformedURLException _ex) {
        Log.e("getInputStream", "Malformed URL Exception: " + _ex.toString());
    } catch (IOException _ex) {
        Log.e("getInputStream", "IO Exception: " + _ex.toString());
    }
    return result;
}