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.openintents.openpgp.keyserver.HkpKeyServer.java

private String submitQuery(String request) throws QueryException, HttpError {
    InetAddress ips[];//ww  w  .  j a  v  a2s. co m
    try {
        ips = InetAddress.getAllByName(mHost);
    } catch (UnknownHostException e) {
        throw new QueryException(e.toString());
    }
    for (int i = 0; i < ips.length; ++i) {
        try {
            String url = "http://" + ips[i].getHostAddress() + ":" + mPort + request;
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(25000);
            conn.connect();
            int response = conn.getResponseCode();
            if (response >= 200 && response < 300) {
                return readAll(conn.getInputStream(), conn.getContentEncoding());
            } else {
                String data = readAll(conn.getErrorStream(), conn.getContentEncoding());
                throw new HttpError(response, data);
            }
        } catch (MalformedURLException e) {
            // nothing to do, try next IP
        } catch (IOException e) {
            // nothing to do, try next IP
        }
    }

    throw new QueryException("querying server(s) for '" + mHost + "' failed");
}

From source file:jenkins.plugins.coverity.CIMInstance.java

private int getURLResponseCode(URL url) throws IOException {
    try {//from  ww w  . j a v  a  2 s.com
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.connect();
        conn.getInputStream();
        return conn.getResponseCode();
    } catch (FileNotFoundException e) {
        return 404;
    }
}

From source file:com.pixem.core.activity.Example.java

/** Called when the activity is first created. */
@Override/*  w ww .  j av  a 2  s  .c o  m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (APP_ID == null) {
        Util.showAlert(this, "Warning",
                "Facebook Applicaton ID must be " + "specified before running this example: see Example.java");
    }

    setContentView(R.layout.facebook);
    mLoginButton = (LoginButton) findViewById(R.id.login);
    mText = (TextView) Example.this.findViewById(R.id.txt);
    mRequestButton = (Button) findViewById(R.id.requestButton);
    mPostButton = (Button) findViewById(R.id.postButton);
    mDeleteButton = (Button) findViewById(R.id.deletePostButton);
    mUploadButton = (Button) findViewById(R.id.uploadButton);

    mFacebook = new Facebook(APP_ID);
    mAsyncRunner = new AsyncFacebookRunner(mFacebook);

    SessionStore.restore(mFacebook, this);
    SessionEvents.addAuthListener(new SampleAuthListener());
    SessionEvents.addLogoutListener(new SampleLogoutListener());
    mLoginButton.init(this, mFacebook);

    mRequestButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            mAsyncRunner.request("me", new SampleRequestListener());
        }
    });
    mRequestButton.setVisibility(mFacebook.isSessionValid() ? View.VISIBLE : View.INVISIBLE);

    mUploadButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Bundle params = new Bundle();
            params.putString("method", "photos.upload");

            URL uploadFileUrl = null;
            try {
                uploadFileUrl = new URL("http://www.facebook.com/images/devsite/iphone_connect_btn.jpg");
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            try {
                HttpURLConnection conn = (HttpURLConnection) uploadFileUrl.openConnection();
                conn.setDoInput(true);
                conn.connect();
                int length = conn.getContentLength();

                byte[] imgData = new byte[length];
                InputStream is = conn.getInputStream();
                is.read(imgData);
                params.putByteArray("picture", imgData);

            } catch (IOException e) {
                e.printStackTrace();
            }

            mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
        }
    });
    mUploadButton.setVisibility(mFacebook.isSessionValid() ? View.VISIBLE : View.INVISIBLE);

    mPostButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            mFacebook.dialog(Example.this, "feed", new SampleDialogListener());
        }
    });
    mPostButton.setVisibility(mFacebook.isSessionValid() ? View.VISIBLE : View.INVISIBLE);
}

From source file:com.sonar.it.jenkins.orchestrator.container.JenkinsDownloader.java

private File downloadUrl(String url, File toFile) {
    try {/*  w  ww . j a v  a2  s .c o m*/
        FileUtils.forceMkdir(toFile.getParentFile());

        HttpURLConnection conn;
        URL u = new URL(url);

        LOG.info("Download: " + u);
        // gets redirected multiple times, including from https -> http, so not done by Java

        while (true) {
            conn = (HttpURLConnection) u.openConnection();
            conn.connect();
            if (conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM
                    || conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) {
                String newLocationHeader = conn.getHeaderField("Location");
                LOG.info("Redirect: " + newLocationHeader);
                conn.disconnect();
                u = new URL(newLocationHeader);
                continue;
            }
            break;
        }

        InputStream is = conn.getInputStream();
        ByteStreams.copy(is, Files.asByteSink(toFile).openBufferedStream());
        LOG.info("Downloaded to: " + toFile);
        return toFile;
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

}

From source file:com.joyent.manta.client.MantaClientSigningIT.java

@Test
public final void testCanCreateSignedOPTIONSUriFromPath() throws IOException, InterruptedException {
    if (config.isClientEncryptionEnabled()) {
        throw new SkipException("Signed URLs are not decrypted by the client");
    }/*w w w .j a v a  2s.c o m*/

    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;

    mantaClient.put(path, TEST_DATA);

    // This will throw an error if the newly inserted object isn't present
    mantaClient.head(path);

    Assert.assertEquals(mantaClient.getAsString(path), TEST_DATA);

    Instant expires = Instant.now().plus(1, ChronoUnit.HOURS);
    URI uri = mantaClient.getAsSignedURI(path, "OPTIONS", expires);

    HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();

    try {
        connection.setReadTimeout(3000);
        connection.setRequestMethod("OPTIONS");
        connection.connect();

        Map<String, List<String>> headers = connection.getHeaderFields();

        if (connection.getResponseCode() != 200) {
            String errorText = IOUtils.toString(connection.getErrorStream(), Charset.defaultCharset());

            if (config.getMantaUser().contains("/")) {
                String msg = String.format("This fails due to an outstanding bug: MANTA-2839.\n%s", errorText);
                throw new SkipException(msg);
            }

            Assert.fail(errorText);
        }

        Assert.assertNotNull(headers);
        Assert.assertEquals(headers.get("Server").get(0), "Manta");
    } finally {
        connection.disconnect();
    }
}

From source file:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java

/**
 * Upload ontology content on specified dataset. Graph used is the default
 * one except if specified//from  w w  w.java 2 s  .  co  m
 * 
 * @param ontology
 * @param datasetName
 * @param graphName
 * @throws IOException
 * @throws HttpException
 */
public static void uploadOntology(InputStream ontology, String datasetName, @Nullable String graphName)
        throws IOException, HttpException {
    graphName = Strings.emptyToNull(graphName);

    logger.info("upload ontology in dataset: " + datasetName + " graph:" + Strings.nullToEmpty(graphName));

    boolean createGraph = (graphName != null) ? true : false;
    String dataSetEncoded = URLEncoder.encode(datasetName, "UTF-8");
    String graphEncoded = createGraph ? URLEncoder.encode(graphName, "UTF-8") : null;

    URL url = new URL(HOST + '/' + dataSetEncoded + "/data" + (createGraph ? "?graph=" + graphEncoded : ""));

    final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();

    String boundary = "------------------" + System.currentTimeMillis()
            + Long.toString(Math.round(Math.random() * 1000));

    httpConnection.setUseCaches(false);
    httpConnection.setRequestMethod("POST");
    httpConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    httpConnection.setRequestProperty("Connection", "keep-alive");
    httpConnection.setRequestProperty("Cache-Control", "no-cache");

    // set content
    httpConnection.setDoOutput(true);
    final OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream());
    out.write(BOUNDARY_DECORATOR + boundary + EOL);
    out.write("Content-Disposition: form-data; name=\"files[]\"; filename=\"ontology.owl\"" + EOL);
    out.write("Content-Type: application/octet-stream" + EOL + EOL);
    out.write(CharStreams.toString(new InputStreamReader(ontology)));
    out.write(EOL + BOUNDARY_DECORATOR + boundary + BOUNDARY_DECORATOR + EOL);
    out.close();

    // handle HTTP/HTTPS strange behaviour
    httpConnection.connect();
    httpConnection.disconnect();

    // handle response
    switch (httpConnection.getResponseCode()) {
    case HttpURLConnection.HTTP_CREATED:
        checkState(createGraph, "bad state - code:" + httpConnection.getResponseCode() + " message: "
                + httpConnection.getResponseMessage());
        break;
    case HttpURLConnection.HTTP_OK:
        checkState(!createGraph, "bad state - code:" + httpConnection.getResponseCode() + " message: "
                + httpConnection.getResponseMessage());
        break;
    default:
        throw new HttpException(
                httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage());
    }

}

From source file:it.baywaylabs.jumpersumo.robot.ServerPolling.java

/**
 * This method is called when invoke <b>execute()</b>.<br />
 * Do not invoke manually. Use: new ServerPolling().execute(url1, url2, url3);
 *
 * @param sUrl List of Url that will be download.
 * @return null if all is going ok.//  w ww . j  a  v a 2 s  .  c om
 */
@Override
protected String doInBackground(String... sUrl) {

    InputStream input = null;
    OutputStream output = null;
    File folder = new File(Constants.DIR_ROBOT);
    String baseName = FilenameUtils.getBaseName(sUrl[0]);
    String extension = FilenameUtils.getExtension(sUrl[0]);
    Log.d(TAG, "FileName: " + baseName + " - FileExt: " + extension);

    if (!folder.exists()) {
        folder.mkdir();
    }
    HttpURLConnection connection = null;
    if (!f.isUrl(sUrl[0]))
        return "Url malformed!";
    try {
        URL url = new URL(sUrl[0]);
        connection = (HttpURLConnection) url.openConnection();
        connection.connect();

        // expect HTTP 200 OK, so we don't mistakenly save error report
        // instead of the file
        if (!sUrl[0].endsWith(".csv") && connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return "Server returned HTTP " + connection.getResponseCode() + " "
                    + connection.getResponseMessage();
        }

        // this will be useful to display download percentage
        // might be -1: server did not report the length
        int fileLength = connection.getContentLength();

        // download the file
        input = connection.getInputStream();
        output = new FileOutputStream(folder.getAbsolutePath() + "/" + baseName + "." + extension);

        byte data[] = new byte[4096];
        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
            // allow canceling with back button
            if (isCancelled()) {
                input.close();
                return null;
            }
            total += count;
            // publishing the progress....
            if (fileLength > 0) // only if total length is known
                publishProgress((int) (total * 100 / fileLength));
            output.write(data, 0, count);
        }
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
        return e.toString();
    } finally {
        try {
            if (output != null)
                output.close();
            if (input != null)
                input.close();
        } catch (IOException ignored) {
        }

        if (connection != null)
            connection.disconnect();
    }
    return null;
}

From source file:info.icefilms.icestream.browse.Location.java

protected static String DownloadPage(URL url, String sendCookie, String sendData, StringBuilder getCookie,
        Callback callback) {//from   www .ja v a  2  s  .  c  om
    // Declare our buffer
    ByteArrayBuffer byteArrayBuffer;

    try {
        // Setup the connection
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (X11; Linux i686; rv:2.0) Gecko/20100101 Firefox/4.0");
        urlConnection.setRequestProperty("Referer", mIceFilmsURL.toString());
        if (sendCookie != null)
            urlConnection.setRequestProperty("Cookie", sendCookie);
        if (sendData != null) {
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            urlConnection.setDoOutput(true);
        }
        urlConnection.setConnectTimeout(callback.GetConnectionTimeout());
        urlConnection.setReadTimeout(callback.GetConnectionTimeout());
        urlConnection.connect();

        // Get the output stream and send the data
        if (sendData != null) {
            OutputStream outputStream = urlConnection.getOutputStream();
            outputStream.write(sendData.getBytes());
            outputStream.flush();
            outputStream.close();
        }

        // Get the cookie
        if (getCookie != null) {
            // Clear the string builder
            getCookie.delete(0, getCookie.length());

            // Loop thru the header fields
            String headerName;
            String cookie;
            for (int i = 1; (headerName = urlConnection.getHeaderFieldKey(i)) != null; ++i) {
                if (headerName.equalsIgnoreCase("Set-Cookie")) {
                    // Get the cookie
                    cookie = GetGroup("([^=]+=[^=;]+)", urlConnection.getHeaderField(i));

                    // Add it to the string builder
                    if (cookie != null)
                        getCookie.append(cookie);

                    break;
                }
            }
        }

        // Get the input stream
        InputStream inputStream = urlConnection.getInputStream();

        // For some reason we can actually get a null InputStream instead of an exception
        if (inputStream == null) {
            Log.e("Ice Stream", "Page download failed. Unable to create Input Stream.");
            if (callback.GetErrorBoolean() == false) {
                callback.SetErrorBoolean(true);
                callback.SetErrorStringID(R.string.browse_page_download_error);
            }
            urlConnection.disconnect();
            return null;
        }

        // Get the file size
        final int fileSize = urlConnection.getContentLength();

        // Create our buffers
        byte[] byteBuffer = new byte[2048];
        byteArrayBuffer = new ByteArrayBuffer(2048);

        // Download the page
        int amountDownloaded = 0;
        int count;
        while ((count = inputStream.read(byteBuffer, 0, 2048)) != -1) {
            // Check if we got canceled
            if (callback.IsCancelled()) {
                inputStream.close();
                urlConnection.disconnect();
                return null;
            }

            // Add data to the buffer
            byteArrayBuffer.append(byteBuffer, 0, count);

            // Update the downloaded amount
            amountDownloaded += count;
        }

        // Close the connection
        inputStream.close();
        urlConnection.disconnect();

        // Check for amount downloaded calculation error
        if (fileSize != -1 && amountDownloaded != fileSize) {
            Log.w("Ice Stream", "Total amount downloaded (" + amountDownloaded + " bytes) does not "
                    + "match reported content length (" + fileSize + " bytes).");
        }
    } catch (SocketTimeoutException exception) {
        Log.e("Ice Stream", "Page download failed.", exception);
        if (callback.GetErrorBoolean() == false) {
            callback.SetErrorBoolean(true);
            callback.SetErrorStringID(R.string.browse_page_timeout_error);
        }
        return null;
    } catch (IOException exception) {
        Log.e("Ice Stream", "Page download failed.", exception);
        if (callback.GetErrorBoolean() == false) {
            callback.SetErrorBoolean(true);
            callback.SetErrorStringID(R.string.browse_page_download_error);
        }
        return null;
    }

    // Convert things to a string
    return new String(byteArrayBuffer.toByteArray());
}

From source file:com.adguard.commons.web.UrlUtils.java

/**
 * Downloads content from the specified url using specified proxy (or do not using it) and timeouts.
 * Returns null if there's an error.//from w ww  .  j  a  va2s .com
 *
 * @param url           url
 * @param proxy         proxy to use
 * @param readTimeout   read timeout
 * @param socketTimeout connection timeout
 * @return Downloaded string
 */
public static String downloadString(URL url, Proxy proxy, int readTimeout, int socketTimeout, String encoding) {
    HttpURLConnection connection = null;
    InputStream inputStream = null;

    try {
        connection = (HttpURLConnection) (proxy == null ? url.openConnection() : url.openConnection(proxy));
        connection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.85 Safari/537.36");
        connection.setReadTimeout(readTimeout);
        connection.setConnectTimeout(socketTimeout);
        connection.connect();
        if (connection.getResponseCode() >= 400) {
            throw new IOException("Response status is " + connection.getResponseCode());
        }

        if (connection.getResponseCode() >= 301) {
            String location = connection.getHeaderField("Location");
            // HttpURLConnection does not follow redirects from HTTP to HTTPS
            // So we handle it manually
            return downloadString(new URL(location), proxy, readTimeout, socketTimeout, encoding);
        }

        if (connection.getResponseCode() == 204) {
            return StringUtils.EMPTY;
        }

        inputStream = connection.getInputStream();
        return IOUtils.toString(inputStream, encoding);
    } catch (IOException ex) {
        if (LOG.isDebugEnabled()) {
            LOG.warn("Error downloading string from {}:\r\n", url, ex);
        } else {
            LOG.warn("Cannot download string from {}: {}", url, ex.getMessage());
        }
        // Ignoring exception
        return null;
    } finally {
        IOUtils.closeQuietly(inputStream);
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.bleum.canton.loadpage.LoadPage.java

private void readContentFromGet(String url) throws IOException {
    HttpURLConnection connection = null;
    BufferedReader reader = null;
    try {//from  w  ww  . j  a  va  2s.c  o m
        URL getUrl = new URL(url);
        connection = (HttpURLConnection) getUrl.openConnection();
        connection.setUseCaches(false);
        connection.setRequestProperty("Cache-Control", "no-cache");
        connection.connect();
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        while ((reader.readLine()) != null) {
            // System.out.println(lines);
        }
    } finally {
        IOUtils.closeQuietly(reader);
        if (connection != null) {
            connection.disconnect();
        }
    }
}