Example usage for java.net URLConnection connect

List of usage examples for java.net URLConnection connect

Introduction

In this page you can find the example usage for java.net URLConnection 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.spinn3r.api.BaseClient.java

protected URLConnection getConnection(String resource) throws IOException {

    URLConnection conn = null;

    try {//from   ww w .  j  a  va  2s.  c  om

        // create the HTTP connection.
        URL request = new URL(resource);
        conn = request.openConnection();

        // set the UserAgent so Spinn3r know which client lib is calling.
        conn.setRequestProperty(USER_AGENT_HEADER, USER_AGENT + "; " + getConfig().getCommandLine());
        conn.setRequestProperty(ACCEPT_ENCODING_HEADER, GZIP_ENCODING);
        conn.setConnectTimeout(20000);
        conn.connect();

    }

    catch (IOException ioe) {

        //create a custom exception message with the right error.
        String message = conn.getHeaderField(null);
        IOException ce = new IOException(message);
        ce.setStackTrace(ioe.getStackTrace());

        throw ce;
    }

    return conn;
}

From source file:io.github.bonigarcia.wdm.BrowserManager.java

protected InputStream openGitHubConnection(URL driverUrl) throws IOException {
    Proxy proxy = createProxy();//from ww w .  jav a 2 s . c  o  m
    URLConnection conn = proxy != null ? driverUrl.openConnection(proxy) : driverUrl.openConnection();
    conn.setRequestProperty("User-Agent", "Mozilla/5.0");
    conn.addRequestProperty("Connection", "keep-alive");

    String gitHubTokenName = WdmConfig.getString("wdm.gitHubTokenName");
    String gitHubTokenSecret = WdmConfig.getString("wdm.gitHubTokenSecret");
    if (!isNullOrEmpty(gitHubTokenName) && !isNullOrEmpty(gitHubTokenSecret)) {
        String userpass = gitHubTokenName + ":" + gitHubTokenSecret;
        String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
        conn.setRequestProperty("Authorization", basicAuth);
    }
    conn.connect();

    return conn.getInputStream();
}

From source file:convcao.com.caoAgent.convcaoNeptusInteraction.java

/**
 * This method is called whenever the AUVs have reached their destinations and new data is to be sent to the server.<br/>
 * As a result, new destinations will be received and vehicles will travel to the new destinations.
 * @throws Exception If there is a problem communicating with the server.
 *//*  w  w  w  .  ja v a 2s .  c o m*/
public void controlLoop() throws Exception {

    TransferData send = localState();
    if (send == null)
        throw new Exception("Unable to compute local state");

    TransferData receive = new TransferData();

    for (int AUV = 0; AUV < AUVS; AUV++) {
        showText(nameTable.get(AUV) + " is at " + send.Location[AUV][0] + ", " + send.Location[AUV][1] + ", "
                + send.Location[AUV][2]);
    }

    Gson gson = new Gson();
    String json = gson.toJson(send);

    PrintWriter writer = null;
    writer = new PrintWriter(SessionID + "_Data.txt", "UTF-8");
    writer.write(json);
    writer.close();

    NeptusLog.pub().info("uploading to convcao..." + json.toString());
    Upload("www.convcao.com", "NEPTUS", "", jTextField1.getText(), new String(jPasswordField1.getPassword()),
            SessionID + "_Data.txt");

    showText("Upload complete, downloading new AUV destinations");

    int receivedTimestep = 0;
    while (!cancel && receivedTimestep < timestep) {
        Thread.sleep(100);

        try {
            URL url = new URL(
                    "http://www.convcao.com/caoagile/FilesFromAgent/NEPTUS/" + SessionID + "_NewActions.txt");
            URLConnection conn = url.openConnection();
            conn.setUseCaches(false);
            conn.connect();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String jsonClient = in.readLine();
            receive = new Gson().fromJson(jsonClient, TransferData.class);
            receivedTimestep = receive.timeStep;
        } catch (IOException ex) {
            NeptusLog.pub().error(ex);
        }
    }

    showText("Received updated positions from convcao");

    timestep++;

    for (int AUV = 0; AUV < receive.Location.length; AUV++) {
        String name = nameTable.get(AUV);
        LocationType loc = coords.convert(receive.Location[AUV][0], receive.Location[AUV][1]);
        loc.setDepth(1 + AUV * 1.5);//coords.convertNoptilusDepthToWgsDepth(receive.Location[AUV][2]));
        destinations.put(name, loc);
        showText(name + " is being sent to " + receive.Location[AUV][0] + ", " + receive.Location[AUV][1]);
    }

    myDeleteFile(SessionID + "_Data.txt");
}

From source file:es.upv.riromu.arbre.main.MainActivity.java

private Bitmap loadBitmap(String url) {
    Bitmap bm = null;/*from w  ww.j  a v  a2s.  c  o  m*/
    InputStream is = null;
    BufferedInputStream bis = null;
    try {
        URLConnection conn = new URL(url).openConnection();
        conn.connect();
        is = conn.getInputStream();
        bis = new BufferedInputStream(is, 8192);
        bm = BitmapFactory.decodeStream(bis);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return bm;
}

From source file:convcao.com.agent.ConvcaoNeptusInteraction.java

/**
 * This method is called whenever the AUVs have reached their destinations and new data is to be sent to the server.<br/>
 * As a result, new destinations will be received and vehicles will travel to the new destinations.
 * @throws Exception If there is a problem communicating with the server.
 *//*from   ww  w .jav  a 2s .  co m*/
public void controlLoop() throws Exception {
    TransferData send = localState();
    if (send == null)
        throw new Exception("Unable to compute local state");

    TransferData receive = new TransferData();

    for (int AUV = 0; AUV < auvs; AUV++) {
        showText(nameTable.get(AUV) + " is at " + send.Location[AUV][0] + ", " + send.Location[AUV][1] + ", "
                + send.Location[AUV][2]);
    }

    Gson gson = new Gson();
    String json = gson.toJson(send);

    PrintWriter writer = null;
    writer = new PrintWriter(sessionID + "_Data.txt", "UTF-8");
    writer.write(json);
    writer.close();

    NeptusLog.pub().info("uploading to convcao..." + json.toString());
    upload("www.convcao.com", "NEPTUS", "", jTextField1.getText(), new String(jPasswordField1.getPassword()),
            sessionID + "_Data.txt");

    showText("Upload complete, downloading new AUV destinations");

    int receivedTimestep = 0;
    while (!cancel && receivedTimestep < timestep) {
        Thread.sleep(100);

        try {
            URL url = new URL(
                    "http://www.convcao.com/caoagile/FilesFromAgent/NEPTUS/" + sessionID + "_NewActions.txt");
            URLConnection conn = url.openConnection();
            conn.setUseCaches(false);
            conn.connect();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String jsonClient = in.readLine();
            receive = new Gson().fromJson(jsonClient, TransferData.class);
            receivedTimestep = receive.timeStep;
        } catch (IOException ex) {
            NeptusLog.pub().error(ex);
        }
    }

    showText("Received updated positions from convcao");

    timestep++;

    for (int AUV = 0; AUV < receive.Location.length; AUV++) {
        String name = nameTable.get(AUV);
        LocationType loc = coords.convert(receive.Location[AUV][0], receive.Location[AUV][1]);
        loc.setDepth(firstVehicleDepth + AUV * depthIncrements);//coords.convertNoptilusDepthToWgsDepth(receive.Location[AUV][2]));
        destinations.put(name, loc);
        showText(name + " is being sent to " + receive.Location[AUV][0] + ", " + receive.Location[AUV][1]);
    }
    // reset arrived states
    for (String auvName : nameTable.values()) {
        arrived.put(auvName, false);
    }

    myDeleteFile(sessionID + "_Data.txt");
}

From source file:de.bps.course.nodes.vc.provider.adobe.AdobeConnectProvider.java

private String sendRequest(Map<String, String> parameters) {
    URL url = createRequestUrl(parameters);
    URLConnection urlConn;

    try {//from www  .  ja  v  a  2s  .co m
        urlConn = url.openConnection();
        // setup url connection
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        // add content type
        urlConn.setRequestProperty("Content-Type", CONTENT_TYPE);
        // add cookie information
        if (cookie != null)
            urlConn.setRequestProperty("Cookie", COOKIE + cookie);

        // send request
        urlConn.connect();

        // read response
        BufferedReader input = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = input.readLine()) != null)
            response.append(line);
        input.close();

        if (isLogDebugEnabled()) {
            logDebug("Requested URL: " + url);
            logDebug("Response: " + response);
        }

        return response.toString();
    } catch (IOException e) {
        logError("Sending request to Adobe Connect failed. Request: " + url.toString(), e);
        return "";
    }
}

From source file:org.nmdp.service.epitope.task.URLProcessor.java

private long refreshFromUrl(URL url, Consumer<InputStream> consumer, long lastModified)
        throws MalformedURLException, IOException {
    logger.debug("trying url: " + url);
    long sourceLastModified = 0;
    final URLConnection urlConnection = url.openConnection();
    if (url.getProtocol().equalsIgnoreCase("ftp")) {
        sourceLastModified = getFtpLastModifiedTime(url);
    } else {/*www .  ja va2s  . c om*/
        sourceLastModified = urlConnection.getLastModified();
    }
    String sourceLastModifiedStr = dateFormat.format(sourceLastModified);
    String lastModifiedStr = dateFormat.format(lastModified);
    if (sourceLastModified == 0) {
        logger.warn("resource has no modification date, forcing refresh...");
    } else if (sourceLastModified < lastModified) {
        logger.warn("resource is older than last modification date (source: " + sourceLastModifiedStr
                + ", last: " + lastModifiedStr + "), leaving it");
        return lastModified;
    } else if (sourceLastModified == lastModified) {
        logger.debug("resource is current (modified: " + lastModifiedStr + ")");
        return lastModified;
    } else {
        logger.info("resource is newer than last modification date, refreshing (source: "
                + sourceLastModifiedStr + ", cache: " + lastModifiedStr + ")");
    }
    urlConnection.connect();
    InputStream is = urlConnection.getInputStream();
    if (unzip) {
        ZipInputStream zis = new ZipInputStream(is);
        ZipEntry entry = zis.getNextEntry();
        logger.info("unzipping, got zip entry: {}", entry.getName());
        is = zis;
    }
    consumer.accept(is);
    is.close();
    return sourceLastModified;
}

From source file:org.apache.hadoop.mapreduce.task.reduce.Fetcher.java

/** 
 * The connection establishment is attempted multiple times and is given up 
 * only on the last failure. Instead of connecting with a timeout of 
 * X, we try connecting with a timeout of x < X but multiple times. 
 *//*ww w .j  a  v  a  2  s .  c o  m*/
private void connect(URLConnection connection, int connectionTimeout) throws IOException {
    int unit = 0;
    if (connectionTimeout < 0) {
        throw new IOException("Invalid timeout " + "[timeout = " + connectionTimeout + " ms]");
    } else if (connectionTimeout > 0) {
        unit = Math.min(UNIT_CONNECT_TIMEOUT, connectionTimeout);
    }
    long startTime = Time.monotonicNow();
    long lastTime = startTime;
    int attempts = 0;
    // set the connect timeout to the unit-connect-timeout
    connection.setConnectTimeout(unit);
    while (true) {
        try {
            attempts++;
            connection.connect();
            break;
        } catch (IOException ioe) {
            long currentTime = Time.monotonicNow();
            long retryTime = currentTime - startTime;
            long leftTime = connectionTimeout - retryTime;
            long timeSinceLastIteration = currentTime - lastTime;
            // throw an exception if we have waited for timeout amount of time
            // note that the updated value if timeout is used here
            if (leftTime <= 0) {
                int retryTimeInSeconds = (int) retryTime / 1000;
                LOG.error("Connection retry failed with " + attempts + " attempts in " + retryTimeInSeconds
                        + " seconds");
                throw ioe;
            }
            // reset the connect timeout for the last try
            if (leftTime < unit) {
                unit = (int) leftTime;
                // reset the connect time out for the final connect
                connection.setConnectTimeout(unit);
            }

            if (timeSinceLastIteration < unit) {
                try {
                    // sleep the left time of unit
                    sleep(unit - timeSinceLastIteration);
                } catch (InterruptedException e) {
                    LOG.warn("Sleep in connection retry get interrupted.");
                    if (stopped) {
                        return;
                    }
                }
            }
            // update the total remaining connect-timeout
            lastTime = Time.monotonicNow();
        }
    }
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.util.Fetcher.java

protected HttpURLConnection getConnection(final String url, final String data, final String requestMethod,
        final long lastFetchTime) throws IOException {
    String method = GET_STR;//  w ww. j  a  v a  2 s . com

    if (requestMethod != null) {
        method = requestMethod;
    }

    LOGGER.info(method + "ing: " + url + "; timeout is " + timeout);

    final URLConnection connection = new URL(url).openConnection();

    connection.setIfModifiedSince(lastFetchTime);

    if (timeout != 0) {
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);
    }

    final HttpURLConnection http = (HttpURLConnection) connection;

    if (connection instanceof HttpsURLConnection) {
        final HttpsURLConnection https = (HttpsURLConnection) connection;
        https.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(final String arg0, final SSLSession arg1) {
                return true;
            }
        });
    }

    http.setInstanceFollowRedirects(false);
    http.setRequestMethod(method);
    http.setAllowUserInteraction(true);

    for (final String key : requestProps.keySet()) {
        http.addRequestProperty(key, requestProps.get(key));
    }

    if (method.equals(POST_STR) && data != null) {
        http.setDoOutput(true); // Triggers POST.

        try (final OutputStream output = http.getOutputStream()) {
            output.write(data.getBytes(UTF8_STR));
        }
    }

    connection.connect();

    return http;
}