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.fashiontec.bodyapps.sync.Sync.java

/**
 * Downloads a file from given URL./*from  ww w . j av  a  2s .com*/
 *
 * @param url
 * @param file
 * @return
 */
public int download(String url, String file) {

    try {
        URL u = new URL(url);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setConnectTimeout(2000);
        c.setRequestProperty("Accept", "application/vnd.valentina.hdf");
        c.connect();

        FileOutputStream f = new FileOutputStream(new File(file));
        InputStream in = c.getInputStream();

        //download code
        byte[] buffer = new byte[1024];
        int len1 = 0;

        while ((len1 = in.read(buffer)) > 0) {
            f.write(buffer, 0, len1);
        }
        f.close();
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
        return -1;
    }
    return 1;
}

From source file:gmusic.api.comm.HttpUrlConnector.java

@Override
public final synchronized String dispatchPost(URI address, FormBuilder form)
        throws IOException, URISyntaxException {
    HttpURLConnection connection = prepareConnection(address, true, "POST");
    if (!Strings.isNullOrEmpty(form.getContentType())) {
        connection.setRequestProperty("Content-Type", form.getContentType());
    }/*from   w  ww.j  av  a  2s  . c o m*/
    connection.connect();
    connection.getOutputStream().write(form.getBytes());
    if (connection.getResponseCode() != 200) {
        throw new IllegalStateException("Statuscode " + connection.getResponseCode() + " not supported");
    }

    String response = IOUtils.toString(connection.getInputStream());

    setCookie(connection);

    if (!isStartup) {
        return response;
    }
    return setupAuthentication(response);
}

From source file:org.digitalcampus.oppia.task.DownloadCourseTask.java

@Override
protected Payload doInBackground(Payload... params) {
    Payload payload = params[0];//w  ww.  j a  va  2  s .  c  om

    Course dm = (Course) payload.getData().get(0);
    DownloadProgress dp = new DownloadProgress();
    try {
        HTTPConnectionUtils client = new HTTPConnectionUtils(ctx);

        String url = client.createUrlWithCredentials(dm.getDownloadUrl());

        Log.d(TAG, "Downloading:" + url);

        URL u = new URL(url);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setDoOutput(true);
        c.connect();
        c.setConnectTimeout(
                Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_connection),
                        ctx.getString(R.string.prefServerTimeoutConnection))));
        c.setReadTimeout(Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_response),
                ctx.getString(R.string.prefServerTimeoutResponse))));

        int fileLength = c.getContentLength();

        String localFileName = dm.getShortname() + "-" + String.format("%.0f", dm.getVersionId()) + ".zip";

        dp.setMessage(localFileName);
        dp.setProgress(0);
        publishProgress(dp);

        Log.d(TAG, "saving to: " + localFileName);

        FileOutputStream f = new FileOutputStream(new File(MobileLearning.DOWNLOAD_PATH, localFileName));
        InputStream in = c.getInputStream();

        byte[] buffer = new byte[1024];
        int len1 = 0;
        long total = 0;
        int progress = 0;
        while ((len1 = in.read(buffer)) > 0) {
            total += len1;
            progress = (int) (total * 100) / fileLength;
            if (progress > 0) {
                dp.setProgress(progress);
                publishProgress(dp);
            }
            f.write(buffer, 0, len1);
        }
        f.close();

        dp.setProgress(100);
        publishProgress(dp);
        dp.setMessage(ctx.getString(R.string.download_complete));
        publishProgress(dp);
        payload.setResult(true);
    } catch (ClientProtocolException cpe) {
        if (!MobileLearning.DEVELOPER_MODE) {
            BugSenseHandler.sendException(cpe);
        } else {
            cpe.printStackTrace();
        }
        payload.setResult(false);
        payload.setResultResponse(ctx.getString(R.string.error_connection));
    } catch (SocketTimeoutException ste) {
        if (!MobileLearning.DEVELOPER_MODE) {
            BugSenseHandler.sendException(ste);
        } else {
            ste.printStackTrace();
        }
        payload.setResult(false);
        payload.setResultResponse(ctx.getString(R.string.error_connection));
    } catch (IOException ioe) {
        if (!MobileLearning.DEVELOPER_MODE) {
            BugSenseHandler.sendException(ioe);
        } else {
            ioe.printStackTrace();
        }
        payload.setResult(false);
        payload.setResultResponse(ctx.getString(R.string.error_connection));
    }

    return payload;
}

From source file:org.jenkinsci.plugins.url_auth.UrlSecurityRealm.java

@Override
protected UserDetails authenticate(String username, String password) throws AuthenticationException {
    try {//  w  ww .j  ava 2  s  .  c  om
        if (username == null || password == null || username.trim().isEmpty() || password.trim().isEmpty()) {
            throw new BadCredentialsException("Username or password can't be empty.");
        }
        String urlString = loginUrl.replace("[username]", username).replace("[password]", password);
        //System.out.println(urlString);
        URL iurl = new URL(urlString);
        HttpURLConnection uc;
        if (testConnection == null) {
            uc = (HttpURLConnection) iurl.openConnection();
        } else {
            uc = testConnection;
        }
        uc.connect();
        if (this.useResponseCode) {
            int response = uc.getResponseCode();
            uc.disconnect();
            if (response != successResponse) {
                throw new BadCredentialsException(
                        String.format("Response %d didn't match %d", response, this.successResponse));
            }
        } else {
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));

            String matchLine = in.readLine().toLowerCase();
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
                matchLine = matchLine.concat(inputLine);
            }
            matchLine = matchLine.trim().toLowerCase();
            System.out.println(matchLine);
            in.close();
            uc.disconnect();
            if (matchLine == null ? this.successString.toLowerCase() != null
                    : !matchLine.equals(this.successString.toLowerCase())) {
                throw new BadCredentialsException(
                        String.format("Response %s didn't match %s", matchLine, this.successString));
            }
        }
        GrantedAuthority[] groups = new GrantedAuthority[0];
        UserDetails d = new User(username, password, true, true, true, true, groups);
        return d;
    } catch (Exception e) {
        throw new AuthenticationServiceException("Failed", e);
    }
}

From source file:abelymiguel.miralaprima.SetMoza.java

private Boolean checkUrlMoza(String url_moza) {
    Boolean result;//from  ww  w.j av a 2s.  c om
    URL url;
    HttpURLConnection conexion;
    try {
        url = new URL(url_moza);
        conexion = (HttpURLConnection) url.openConnection();
        conexion.connect();
        BufferedReader respContent;
        respContent = new BufferedReader(new InputStreamReader(conexion.getInputStream()));
        respContent.close();
        conexion.disconnect();
        result = true;
    } catch (IOException e) {
        Logger.getLogger(GetMoza.class.getName()).log(Level.WARNING, null, e);
        result = false;
    }

    return result;
}

From source file:com.tarsoft.openlibra.OpenLibraClient.java

private Bitmap drawableFromUrl(String url) throws java.net.MalformedURLException, java.io.IOException {
    Bitmap x;/*from  w  w w. j av a  2s.  com*/

    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setRequestProperty("User-agent", "Mozilla/4.0");

    connection.connect();
    InputStream input = connection.getInputStream();

    x = BitmapFactory.decodeStream(input);
    return x;
}

From source file:com.sap.wec.adtreco.be.ODataClientService.java

private InputStream execute(final String relativeUri, final String contentType, final String httpMethod)
        throws IOException, MalformedURLException {
    final HttpURLConnection connection = initializeConnection(relativeUri, contentType, httpMethod);
    connection.connect();
    checkStatus(connection);/*  www  .  ja  va  2 s  .c om*/
    final InputStream content = connection.getInputStream();
    return content;
}

From source file:fm.krui.kruifm.TrackUpdateHandler.java

/**
 * Downloads album art from passed URL using the last.fm api.
 * @param url Web safe location of image as URL.
 * @return Bitmap of the image requested
 *//*  w  ww  . j  a  v  a2  s.  c  o  m*/
protected Bitmap downloadAlbumArt(String url) {

    Bitmap bitmap;

    // Check if an album art URL was returned. If there's no location, there's no point in wasting resources trying to download nothing.
    if (artUrl.equals("*NO_ART*") == false) {

        // Download the image from URL
        try {
            HttpURLConnection connection;
            connection = (HttpURLConnection) new URL(url).openConnection();
            connection.connect();
            InputStream input = connection.getInputStream();
            bitmap = BitmapFactory.decodeStream(input);
            return bitmap;

        } catch (MalformedURLException e) {
            Log.e(TAG, "Malformed URL detected when downloading album art: ");
            e.printStackTrace();
        } catch (IOException e) {
            Log.e(TAG, "Failed to process album art: ");
            e.printStackTrace();
        }
    }

    // If the download fails or image doesn't exist, display the default KRUI background image.
    bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.krui_background_logo);
    return bitmap;
}

From source file:com.opentransport.rdfmapper.nmbs.NetworkDisturbanceFetcher.java

private void scrapeNetworkDisturbanceWebsite(String language, String _url) {
    Document doc;//from   w w  w  .ja  v a2s  . c  o m
    int i = 0;
    //English Version
    try {
        URL url = new URL(_url);
        HttpURLConnection request = (HttpURLConnection) url.openConnection();
        request.connect();

        // Convert to a JSON object to print data
        JsonParser jp = new JsonParser(); //from gson
        JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
        JsonArray disturbances = root.getAsJsonObject().getAsJsonArray("him");

        for (JsonElement el : disturbances) {
            JsonObject obj = (JsonObject) el;

            String header = obj.get("header").getAsString();
            String description = obj.get("text").getAsString();
            String urls = ""; // todo check JsonNull

            String begin = obj.get("begin").getAsString(); // dd.MM.yyyy HH:mm
            String end = obj.get("end").getAsString(); // dd.MM.yyyy HH:mm
            SimpleDateFormat df = new SimpleDateFormat("dd.MM.yy HH:mm");
            df.setTimeZone(TimeZone.getTimeZone("Europe/Brussels"));

            Date date;
            long startEpoch, endEpoch;
            try {
                date = df.parse(begin);
                startEpoch = date.getTime() / 1000;
                date = df.parse(end);
                endEpoch = date.getTime() / 1000;
            } catch (ParseException ex) {
                // When time range is missing, take 12 hours before and after
                startEpoch = new Date().getTime() - 43200;
                endEpoch = new Date().getTime() + 43200;

                Logger.getLogger(NetworkDisturbanceFetcher.class.getName()).log(Level.SEVERE, null, ex);
            }

            int startStationId, endStationId, impactStationId;
            if (obj.has("startstation_extId")) {
                startStationId = obj.get("startstation_extId").getAsInt();
            } else {
                startStationId = -1;
            }
            if (obj.has("endstation_extId")) {
                endStationId = obj.get("endstation_extId").getAsInt();
            } else {
                endStationId = -1;
            }
            if (obj.has("impactstation_extId")) {
                impactStationId = obj.get("impactstation_extId").getAsInt();
            } else {
                impactStationId = -1;
            }

            String id = obj.get("id").getAsString();

            NetworkDisturbance disturbance = new NetworkDisturbance(header, description, urls, language,
                    startEpoch, endEpoch, startStationId, endStationId, impactStationId, id);

            networkDisturbances.add(disturbance);
        }

    } catch (IOException ex) {
        Logger.getLogger(NetworkDisturbanceFetcher.class.getName()).log(Level.SEVERE, null, ex);
        errorWriter.writeError(ex.toString());
    }

}

From source file:io.mesosphere.mesos.frameworks.cassandra.scheduler.api.AbstractApiControllerTest.java

@NotNull
protected Tuple2<Integer, String> fetchText(final String rel, final String expectedContentType)
        throws Exception {
    final HttpURLConnection conn = (HttpURLConnection) resolve(rel).toURL().openConnection();
    try {// ww w  .  j a va 2  s .co m
        conn.setRequestProperty("Accept", expectedContentType);
        conn.connect();

        final int responseCode = conn.getResponseCode();

        InputStream in;
        try {
            in = conn.getInputStream();
        } catch (final IOException e) {
            in = conn.getErrorStream();
        }
        if (in == null) {
            return Tuple2.tuple2(responseCode, "");
        }

        assertEquals(expectedContentType, conn.getHeaderField("Content-Type"));

        try {
            final StringBuilder sb = new StringBuilder();
            int rd;
            while ((rd = in.read()) != -1) {
                sb.append((char) rd);
            }
            return Tuple2.tuple2(responseCode, sb.toString());
        } finally {
            in.close();
        }
    } finally {
        conn.disconnect();
    }
}