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:org.droidparts.http.worker.HttpURLConnectionWorker.java

private static int connectAndGetResponseCodeOrThrow(HttpURLConnection conn) throws HTTPException {
    try {//  ww  w .  j a v  a2 s. c om
        conn.connect();
        int respCode = conn.getResponseCode();
        if (isErrorResponseCode(respCode)) {
            HTTPInputStream is = HTTPInputStream.getInstance(conn, (conn.getErrorStream() != null));
            throw new HTTPException(respCode, is.readAndClose());
        }
        return respCode;
    } catch (HTTPException e) {
        throw e;
    } catch (Exception e) {
        throw new HTTPException(e);
    }

}

From source file:Main.java

/**
 * Downloads a file via HTTP(S) GET to the given path. This function cannot be called from the
 * UI thread. Android does not allow it.
 *
 * @param urlString Url to the ressource to download.
 * @param file      file to be written to.
 * @param overwrite if file exists, overwrite?
 * @return flase if download was not successful. If successful, true.
 *//*from w w w .j  a  va 2s  .c  om*/
private static Boolean fileDownloadHttp(String urlString, File file, Boolean overwrite) {
    HashMap<String, String> result = null;
    URL url = null;
    //        File temp;

    try {
        url = new URL(urlString);

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setReadTimeout(200000);
        urlConnection.connect();
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());

        FileOutputStream outputStream = new FileOutputStream(file);

        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = in.read(bytes)) != -1) {
            outputStream.write(bytes, 0, read);
        }

        in.close();
        outputStream.close();
        urlConnection.disconnect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    Log.d(TAG, "File download: " + file.getAbsolutePath() + url.getFile() + "overwrite " + overwrite
            + "exists? " + file.exists());
    return true;
}

From source file:Main.java

/**
 * This method fetches data from a given url
 *
 * @param strUrl Url from which the data will be fetched
 * @return A String representing the resource obtained in the connection
 * @throws IOException If something went wrong with the connection
 */// w w w  .  j  a  va2 s .  c  om
public static String getDataFromUrl(String strUrl) throws IOException {
    InputStream iStream;
    HttpURLConnection urlConnection;
    URL url = new URL(strUrl);

    // Creating an http connection to communicate with url
    urlConnection = (HttpURLConnection) url.openConnection();

    // Connecting to url
    urlConnection.connect();

    // Reading data from url
    iStream = urlConnection.getInputStream();

    BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

    StringBuilder sb = new StringBuilder();

    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line);
    }
    br.close();
    iStream.close();
    urlConnection.disconnect();
    return sb.toString();
}

From source file:de.forsthaus.backend.util.IpLocator.java

/**
 * Gets the content for a given url. This method makes a connection, gets
 * the response from the url.//from w ww .  j a v a 2  s  . c o m
 * 
 * A RuntimeException is throws is the status code of the response is not
 * 200.
 * 
 * @param url
 *            The url to open.
 * @return HTML response
 * @throws IOException
 */
private static List<String> getContent(URL url) throws IOException {

    final HttpURLConnection http = (HttpURLConnection) url.openConnection();
    try {
        http.connect();

        final int code = http.getResponseCode();
        if (code != 200)
            throw new IOException(
                    "IP Locator failed to get the location. Http Status code : " + code + " [" + url + "]");
        return getContent(http);
    } finally {
        http.disconnect();
    }
}

From source file:org.cytoscape.app.internal.net.server.AddAccessControlAllowOriginHeaderAfterResponseTest.java

private static HttpURLConnection connectToURL(String urlString, String method) throws Exception {
    final URL url = new URL(urlString);
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(method);
    connection.setDoOutput(true);/*from w  w w  .  j a  va  2 s .c o m*/
    connection.setConnectTimeout(1000);
    connection.connect();
    return connection;
}

From source file:org.cytoscape.app.internal.net.server.CyHttpdImplTest.java

private static HttpURLConnection connectToURL(String urlString, String method) throws Exception {
    final URL url = new URL(urlString);
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(method);
    connection.setDoOutput(true);//from   www .  jav  a  2s.c  o  m
    connection.connect();
    return connection;
}

From source file:Main.java

public static Bitmap downLoadBitmap(String httpUrl) {
    InputStream inputStream = null;
    try {//from  ww  w  .j  a  va  2 s  .  c o m
        URL url = new URL(httpUrl);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        conn.setReadTimeout(5000);
        conn.setConnectTimeout(5000);
        conn.connect();
        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            inputStream = conn.getInputStream();

            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

            return bitmap;
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return null;
}

From source file:com.adguard.compiler.UrlUtils.java

public static String downloadString(URL url, String encoding, String userAgent) throws IOException {

    HttpURLConnection connection = null;
    InputStream inputStream = null;

    try {// w w w  .j  a v  a  2  s .co  m
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("User-Agent", userAgent);
        connection.connect();
        inputStream = connection.getInputStream();
        return IOUtils.toString(inputStream, encoding);
    } finally {
        IOUtils.closeQuietly(inputStream);
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:Main.java

public static void DownloadFile(String u) {
    try {/*from   w  w  w  . ja  v a2s.  c o  m*/
        Logd(TAG, "Starting download of: " + u);
        URL url = new URL(u);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.connect();
        //File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        checkStorageDir();
        File storageDir = new File(
                Environment.getExternalStorageDirectory() + "/Android/data/com.nowsci.odm/.storage");
        File file = new File(storageDir, getFileName(u));
        Logd(TAG, "Storage directory: " + storageDir.toString());
        Logd(TAG, "File name: " + file.toString());
        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();
        Logd(TAG, "File written");
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.dlshouwen.core.api.controller.ApiController.java

/**
 * base64/*from   ww w  .j av  a2 s.co  m*/
 * @param path
 * @return 
 */
public static String GetImageStr(String path) {//Base64??
    InputStream in = null;
    byte[] data = null;
    //?
    try {
        URL url = new URL(path);
        HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
        httpUrl.connect();
        in = httpUrl.getInputStream();
        data = new byte[in.available()];
        in.read(data);
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    //Base64?
    BASE64Encoder encoder = new BASE64Encoder();
    return encoder.encode(data);//Base64?
}