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:french_toast_mafia.waitr.MainActivity.java

/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException {
    String data = "";
    InputStream iStream = null;/*from   w  ww . j a  v a  2  s. c om*/
    HttpURLConnection urlConnection = null;
    try {
        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));

        StringBuffer sb = new StringBuffer();

        String line = "";
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        data = sb.toString();

        br.close();

    } catch (Exception e) {
        // Log.d("Exception while downloading url", e.toString());
    } finally {
        iStream.close();
        urlConnection.disconnect();
    }

    return data;
}

From source file:com.example.ronald.tracle.RegistrationIntentService.java

private String downloadContent(String myurl) throws IOException {
    InputStream is = null;//from   ww w .  j  a  v a  2 s  .  c o  m
    int length = 500;

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        conn.connect();
        int response = conn.getResponseCode();
        Log.d(TAG, "The response is: " + response);
        is = conn.getInputStream();

        // Convert the InputStream into a string
        String contentAsString = convertInputStreamToString(is, length);
        return contentAsString;
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:com.facebook.android.Example.java

/** Called when the activity is first created. */
@Override/* w  ww.java  2s  .  co 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.main);
    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.joyent.manta.client.MantaClientSigningIT.java

@Test
public final void testCanCreateSignedHEADUriFromPath() throws IOException {
    if (config.isClientEncryptionEnabled()) {
        throw new SkipException("Signed URLs are not decrypted by the client");
    }/*  w  w  w  . j  av  a2  s  . 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);

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

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

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

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

        if (connection.getResponseCode() != 200) {
            Assert.fail(IOUtils.toString(connection.getErrorStream(), Charset.defaultCharset()));
        }

        Assert.assertNotNull(headers);
        Assert.assertEquals(TEST_DATA.length(), connection.getContentLength());
    } finally {
        connection.disconnect();
    }
}

From source file:com.finlay.geomonsters.WeatherManager.java

private String getWeatherData(String address) {
    Log.v(TAG, "getWeatherData: " + address);
    HttpURLConnection con = null;
    InputStream is = null;//  w w  w.  ja  va2 s  .c  om

    try {
        con = (HttpURLConnection) (new java.net.URL(address)).openConnection();
        con.setRequestMethod("GET");
        con.setDoInput(true);
        con.setDoOutput(true);
        con.connect();

        Log.v(TAG, "Open Weather connected.");
        _parent.appendMessage("Open Weather connected.");

        // Let's read the response
        StringBuffer buffer = new StringBuffer();
        is = con.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null)
            buffer.append(line + "\r\n");

        is.close();
        con.disconnect();
        return buffer.toString();

    } catch (Throwable t) {
        Log.e(TAG, t.getMessage());
    } finally {
        try {
            is.close();
        } catch (Throwable t) {
        }
        try {
            con.disconnect();
        } catch (Throwable t) {
        }
    }

    return null;
}

From source file:com.jittr.android.facebook.Example.java

/** Called when the activity is first created. */
@Override//from  w w  w. ja  va  2 s  . c  om
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");
    }

    // mFacebook.
    setContentView(R.layout.mainfacebook);
    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();
    mAsyncRunner = new AsyncFacebookRunner(mFacebook);

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

    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());
        }
    });
    mUploadButton.setVisibility(mFacebook.isSessionValid() ? View.VISIBLE : View.INVISIBLE);

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

From source file:edu.stanford.mobisocial.dungbeetle.facebook.FacebookInterfaceActivity.java

/** Called when the activity is first created. */
@Override//from w  w w . j av  a 2 s .  co 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 FacebookInterfaceActivity.java");
    }

    setContentView(R.layout.facebook);
    mLoginButton = (LoginButton) findViewById(R.id.login);
    mText = (TextView) FacebookInterfaceActivity.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(FacebookInterfaceActivity.this, "feed", new SampleDialogListener());
        }
    });
    mPostButton.setVisibility(mFacebook.isSessionValid() ? View.VISIBLE : View.INVISIBLE);
}

From source file:cn.leancloud.diamond.server.service.NotifyService.java

/**
 * http get/*from   w w  w. ja v a  2  s  .co m*/
 * 
 * @param urlString
 * @return
 */
private String invokeURL(String urlString) {
    HttpURLConnection conn = null;
    URL url = null;
    try {
        url = new URL(urlString);
        conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(TIMEOUT);
        conn.setReadTimeout(TIMEOUT);
        conn.setRequestMethod("GET");
        conn.connect();
        InputStream urlStream = conn.getInputStream();
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(urlStream));
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } finally {
            if (reader != null)
                reader.close();
        }
        return sb.toString();

    } catch (Exception e) {
        log.error("http,url=" + urlString, e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return "error";
}

From source file:com.taobao.diamond.server.service.NotifyService.java

/**
 * http get//from w w w.  j  a  v  a  2  s. co m
 * 
 * @param urlString
 * @return
 */
private String invokeURL(String urlString) {
    HttpURLConnection conn = null;
    URL url = null;
    try {
        url = new URL(urlString);
        conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(TIMEOUT);
        conn.setReadTimeout(TIMEOUT);
        conn.setRequestMethod("GET");
        conn.connect();
        InputStream urlStream = conn.getInputStream();
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(urlStream));
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } finally {
            if (reader != null)
                reader.close();
        }
        return sb.toString();

    } catch (Exception e) {
        log.error("http,url=" + urlString, e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return "error";
}

From source file:crow.weibo.util.WeiboUtil.java

public static String multipartPost(HttpURLConnection conn, List<PostParameter> params) throws IOException {
    OutputStream os;//  w  w w  .j  a  v a 2s.c  o  m
    List<PostParameter> dataparams = new ArrayList<PostParameter>();
    for (PostParameter key : params) {
        if (key.isFile()) {
            dataparams.add(key);
        }
    }

    String BOUNDARY = Util.md5(String.valueOf(System.currentTimeMillis()));

    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Charsert", "UTF-8");

    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);

    ByteArrayBuffer buff = new ByteArrayBuffer(1000);

    for (PostParameter p : params) {
        byte[] arr = p.toMultipartByte(BOUNDARY, "UTF-8");
        buff.append(arr, 0, arr.length);
    }
    String end = "--" + BOUNDARY + "--" + "\r\n";
    byte[] endArr = end.getBytes();
    buff.append(endArr, 0, endArr.length);

    conn.setRequestProperty("Content-Length", buff.length() + "");
    conn.connect();
    os = new BufferedOutputStream(conn.getOutputStream());
    os.write(buff.toByteArray());
    buff.clear();
    os.flush();
    String response = "";
    response = Util.inputStreamToString(conn.getInputStream());
    return response;
}