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:foam.blob.RestBlobService.java

@Override
public Blob find_(X x, Object id) {
    InputStream is = null;/* w  w w . ja v  a  2s.c  o m*/
    ByteArrayOutputStream os = null;
    HttpURLConnection connection = null;

    try {
        URL url = new URL(this.address_ + "/" + id.toString());
        connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("GET");
        connection.connect();

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK || connection.getContentLength() == -1) {
            throw new RuntimeException("Failed to find blob");
        }

        is = new BufferedInputStream(connection.getInputStream());
        os = new ByteArrayOutputStream();

        int read = 0;
        byte[] buffer = new byte[BUFFER_SIZE];
        while ((read = is.read(buffer, 0, BUFFER_SIZE)) != -1) {
            os.write(buffer, 0, read);
        }

        return new ByteArrayBlob(os.toByteArray());
    } catch (Throwable t) {
        throw new RuntimeException(t);
    } finally {
        IOUtils.closeQuietly(os);
        IOUtils.closeQuietly(is);
        IOUtils.close(connection);
    }
}

From source file:alluxio.worker.block.BlockWorkerClientRestApiTest.java

@Test
public void readBlock() throws Exception {
    // Write a block and acquire a lock for it.
    mBlockWorker.createBlock(SESSION_ID, BLOCK_ID, TIER_ALIAS, INITIAL_BYTES);
    BlockWriter writer = mBlockWorker.getTempBlockWriterRemote(SESSION_ID, BLOCK_ID);
    writer.append(BYTE_BUFFER);/* ww w  .  ja v a2 s  .c  o  m*/
    writer.close();
    mBlockWorker.commitBlock(SESSION_ID, BLOCK_ID);
    long lockId = mBlockWorker.lockBlock(SESSION_ID, BLOCK_ID);

    Map<String, String> params = new HashMap<>();
    params.put("blockId", Long.toString(BLOCK_ID));
    params.put("sessionId", Long.toString(SESSION_ID));
    params.put("lockId", Long.toString(lockId));
    params.put("offset", "0");
    params.put("length", Long.toString(INITIAL_BYTES));

    TestCase testCase = new TestCase(mHostname, mPort,
            getEndpoint(BlockWorkerClientRestServiceHandler.READ_BLOCK), params, HttpMethod.GET, BYTE_BUFFER);

    HttpURLConnection connection = (HttpURLConnection) testCase.createURL().openConnection();
    connection.setRequestMethod(testCase.getMethod());
    connection.connect();
    Assert.assertEquals(testCase.getEndpoint(), Response.Status.OK.getStatusCode(),
            connection.getResponseCode());
    Assert.assertEquals(new String(BYTE_BUFFER.array()), testCase.getResponse(connection));
}

From source file:com.ejisto.modules.dao.remote.BaseRemoteDao.java

private HttpURLConnection openConnection(String requestPath, String method) throws IOException {
    String destination = serverAddress + defaultIfEmpty(requestPath, "/");
    log.log(Level.FINEST, "url destination: " + destination);
    HttpURLConnection connection = (HttpURLConnection) new URL(destination).openConnection();
    connection.setDoInput(true);/*from w w w. j  a va  2  s .  co  m*/
    connection.setDoOutput(true);
    if (method != null) {
        connection.setRequestMethod(method.toUpperCase());
    }
    connection.connect();
    return connection;
}

From source file:com.sastix.cms.server.services.content.HashedDirectoryServiceTest.java

private int checkIfUrlExists(final URL url) {
    try {//from   www . ja  v a2 s  . co m
        final HttpURLConnection huc = (HttpURLConnection) url.openConnection();
        huc.setRequestMethod("GET"); //OR  huc.setRequestMethod ("HEAD");
        huc.connect();
        return huc.getResponseCode();
    } catch (IOException e) {
        //eat it
    }
    return 400;
}

From source file:freemarker.test.servlet.WebAppTestCase.java

protected final HTTPResponse getHTTPResponse(String webAppName, String webAppRelURL) throws Exception {
    if (webAppName.startsWith("/") || webAppName.endsWith("/")) {
        throw new IllegalArgumentException("\"webAppName\" can't start or end with \"/\": " + webAppName);
    }/*w w w.  java  2s  .  c  om*/
    if (webAppRelURL.startsWith("/") || webAppRelURL.endsWith("/")) {
        throw new IllegalArgumentException("\"webappRelURL\" can't start or end with \"/\": " + webAppRelURL);
    }

    ensureWebAppIsDeployed(webAppName);

    final URI uri = new URI("http://localhost:" + server.getConnectors()[0].getLocalPort() + "/" + webAppName
            + "/" + webAppRelURL);

    final HttpURLConnection httpCon = (HttpURLConnection) uri.toURL().openConnection();
    httpCon.connect();
    try {
        LOG.debug("HTTP GET: {}", uri);

        final int responseCode = httpCon.getResponseCode();

        final String content;
        if (responseCode == 200) {
            InputStream in = httpCon.getInputStream();
            try {
                content = IOUtils.toString(in, "UTF-8");
            } finally {
                in.close();
            }
        } else {
            content = null;
        }

        return new HTTPResponse(responseCode, httpCon.getResponseMessage(), content, uri);
    } finally {
        httpCon.disconnect();
    }
}

From source file:luan.com.flippit.GcmIntentService.java

private String extraMIMEOnline(String urlStr) {
    String contentType = "";
    try {/*from w  w w . j  av  a2 s . co  m*/
        URL url = new URL(urlStr);
        HttpURLConnection connection = null;
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("HEAD");
        connection.connect();
        contentType = connection.getContentType();
        Log.i(MyActivity.TAG, getClass().getName() + ": " + "Extra content type: " + contentType);
        if (contentType != null) {
            contentType = "web";
        }

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

From source file:com.graphhopper.http.NominatimGeocoder.java

HttpURLConnection openConnection(String url) throws IOException {
    HttpURLConnection hConn = (HttpURLConnection) new URL(url).openConnection();
    ;/*www. jav  a2s. com*/
    hConn.setRequestProperty("User-Agent", userAgent);
    hConn.setRequestProperty("content-charset", "UTF-8");
    hConn.setConnectTimeout(timeoutInMillis);
    hConn.setReadTimeout(timeoutInMillis);
    hConn.connect();
    return hConn;
}

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

@Override
protected Payload doInBackground(Payload... params) {
    Payload payload = params[0];//from   ww  w  . jav  a  2 s.co  m
    for (Object o : payload.getData()) {
        Media m = (Media) o;
        File file = new File(MobileLearning.MEDIA_PATH, m.getFilename());
        try {

            URL u = new URL(m.getDownloadUrl());
            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();

            DownloadProgress dp = new DownloadProgress();
            dp.setMessage(m.getFilename());
            dp.setProgress(0);
            publishProgress(dp);

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

            MessageDigest md = MessageDigest.getInstance("MD5");
            in = new DigestInputStream(in, md);

            byte[] buffer = new byte[8192];
            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);

            // check the file digest matches, otherwise delete the file 
            // (it's either been a corrupted download or it's the wrong file)
            byte[] digest = md.digest();
            String resultMD5 = "";

            for (int i = 0; i < digest.length; i++) {
                resultMD5 += Integer.toString((digest[i] & 0xff) + 0x100, 16).substring(1);
            }

            Log.d(TAG, "supplied   digest: " + m.getDigest());
            Log.d(TAG, "calculated digest: " + resultMD5);

            if (!resultMD5.contains(m.getDigest())) {
                this.deleteFile(file);
                payload.setResult(false);
                payload.setResultResponse(ctx.getString(R.string.error_media_download));
            } else {
                payload.setResult(true);
                payload.setResultResponse(ctx.getString(R.string.success_media_download, m.getFilename()));
            }
        } catch (ClientProtocolException e1) {
            e1.printStackTrace();
            payload.setResult(false);
            payload.setResultResponse(ctx.getString(R.string.error_media_download));
        } catch (IOException e1) {
            e1.printStackTrace();
            this.deleteFile(file);
            payload.setResult(false);
            payload.setResultResponse(ctx.getString(R.string.error_media_download));
        } catch (NoSuchAlgorithmException e) {
            if (!MobileLearning.DEVELOPER_MODE) {
                BugSenseHandler.sendException(e);
            } else {
                e.printStackTrace();
            }
            payload.setResult(false);
            payload.setResultResponse(ctx.getString(R.string.error_media_download));
        }
    }
    return payload;
}

From source file:de.tudresden.inf.rn.mobilis.clientservices.socialnetwork.SocialNetworkManager.java

public void loginOAuth2() throws OAuthMessageSignerException, OAuthNotAuthorizedException,
        OAuthExpectationFailedException, OAuthCommunicationException, IOException {
    OAuthConsumer consumer = new DefaultOAuthConsumer(getConsumerKey(), getConsumerSecret());

    OAuthProvider provider = new DefaultOAuthProvider(getRequestTokenURL(), getAccessTokenURL(),
            getAuthorizeURL());//from  w w w .j  a  v  a 2 s  . c  om

    Log.v(TAG, "Fetching request token ...");

    // we do not support callbacks, thus pass OOB
    String authUrl = provider.retrieveRequestToken(consumer, OAuth.OUT_OF_BAND);

    Log.v(TAG, "Request token: " + consumer.getToken());
    Log.v(TAG, "Token secret: " + consumer.getTokenSecret());

    Log.v(TAG, "Now visit:\n" + authUrl + "\n... and grant this app authorization");
    Log.v(TAG, "Enter the PIN code and hit ENTER when you're done:");

    //      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    //      String pin = br.readLine();
    String pin = "abc";

    System.out.println("Fetching access token ...");

    provider.retrieveAccessToken(consumer, pin);

    Log.v(TAG, "Access token: " + consumer.getToken());
    Log.v(TAG, "Token secret: " + consumer.getTokenSecret());

    URL url = new URL("http://twitter.com/statuses/mentions.xml");
    HttpURLConnection request = (HttpURLConnection) url.openConnection();

    consumer.sign(request);

    Log.v(TAG, "Sending request...");
    request.connect();

    Log.v(TAG, "Response: " + request.getResponseCode() + " " + request.getResponseMessage());

}

From source file:com.jug6ernaut.android.utilites.FileDownloader.java

public File downloadFile(String serverUrl, String fileToFetch, File outputFile) throws IOException {
    //File outputFile = null;

    String urlToFetch = serverUrl + fileToFetch;
    URL url = new URL(urlToFetch);
    HttpURLConnection c = (HttpURLConnection) url.openConnection();
    c.setRequestMethod("GET");
    c.setDoOutput(true);//from   ww  w.  ja v a 2 s  . co  m
    c.connect();

    File dir = outputFile.getParentFile();
    dir.mkdirs();

    FileOutputStream fos = new FileOutputStream(outputFile);

    InputStream is = c.getInputStream();

    byte[] buffer = new byte[1024];
    int len1 = 0;
    while ((len1 = is.read(buffer)) != -1) {
        fos.write(buffer, 0, len1);
    }
    fos.close();
    is.close();

    //pd.dismiss();
    return outputFile;
}