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:com.jeffrodriguez.webtools.client.URLConnectionWebClientImpl.java

@Override
public String getString(String url) throws IOException {
    logger.log(Level.INFO, "Getting String from {0}", url);

    // Build and connect
    HttpURLConnection connection = buildConnection(url);
    connection.connect();

    // Check for errors
    checkForErrors(connection);//from   w  w w  .ja va  2s.co m

    // Get the result
    return disconnectAndReturn(connection, IOUtils.toString(connection.getInputStream(), "ISO-8859-1"));
}

From source file:com.jeffrodriguez.webtools.client.URLConnectionWebClientImpl.java

@Override
public Document getDocument(String url) throws IOException, ParserConfigurationException, SAXException {
    logger.log(Level.INFO, "Getting Document from {0}", url);

    // Build and connect
    HttpURLConnection connection = buildConnection(url);
    connection.connect();

    // Check for errors
    checkForErrors(connection);//from  www.jav  a2  s  .  c om

    // Get the result
    return disconnectAndReturn(connection, buildDocument(connection.getInputStream()));
}

From source file:com.jeffrodriguez.webtools.client.URLConnectionWebClientImpl.java

@Override
public XML getXML(String url) throws IOException, ParserConfigurationException, SAXException {
    logger.log(Level.INFO, "Getting Document from {0}", url);

    // Build and connect
    HttpURLConnection connection = buildConnection(url);
    connection.connect();

    // Check for errors
    checkForErrors(connection);//from  www.  j a va 2  s.  c  o  m

    // Get the result
    Document document = buildDocument(connection.getInputStream());
    return disconnectAndReturn(connection, new XML(document));
}

From source file:com.jeffrodriguez.webtools.client.URLConnectionWebClientImpl.java

@Override
public JSOG getJsog(String url) throws IOException {
    logger.log(Level.INFO, "Getting JSOG from {0}", url);

    // Build and connect
    HttpURLConnection connection = buildConnection(url);
    connection.connect();

    // Check for errors
    checkForErrors(connection);/*from w  ww  .  j  a  v a 2 s .co m*/

    // Get the result
    return disconnectAndReturn(connection,
            JSOG.parse(IOUtils.toString(connection.getInputStream(), "ISO-8859-1")));
}

From source file:com.example.maproot.MainActivity.java

private String downloadUrl(String strUrl) throws IOException {
    String data = "";
    InputStream iStream = null;/*from   w  w w  . j  a va  2 s  . c om*/
    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(strUrl);

        urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection.connect();

        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:org.csware.ee.utils.Tools.java

public static String GetDataByPost(String httpUrl, String parMap) {
    try {//from ww w . j a  v  a  2  s .co  m
        URL url = new URL(httpUrl);// 
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestMethod("POST"); // ?
        connection.setRequestProperty("Accept", "application/json"); // ??
        connection.setRequestProperty("Content-Type", "application/json"); // ????
        connection.connect();
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8?
        out.append(parMap);
        out.flush();
        out.close();
        // ??
        int length = (int) connection.getContentLength();// ?
        InputStream is = connection.getInputStream();
        if (length != -1) {
            byte[] data = new byte[length];
            byte[] temp = new byte[1024];
            int readLen = 0;
            int destPos = 0;
            while ((readLen = is.read(temp)) > 0) {
                System.arraycopy(temp, 0, data, destPos, readLen);
                destPos += readLen;
            }
            String result = new String(data, "UTF-8"); // utf-8?
            return result;
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.out.println("aa:  " + e.getMessage());
    }
    return "error"; // ?
}

From source file:com.jiramot.foursquare.android.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 *
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 *
 * @param url - the resource to open: must be a welformed URL
 * @param method - the HTTP method to use ("GET", "POST", etc.)
 * @param params - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String/*from w w w  .  j  a  v a2 s.c om*/
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Log.d("Foursquare-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FoursquareAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).getBytes());

            }
        }
        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:com.orange.oidc.tim.service.HttpOpenidConnect.java

static String getUserInfo(String server_url, String access_token) {
    // android.os.Debug.waitForDebugger();

    // check if server is valid
    if (isEmpty(server_url) || isEmpty(access_token)) {
        return null;
    }//w w  w  .  ja v a2s  .  co  m

    String userinfo_endpoint = getEndpointFromConfigOidc("userinfo_endpoint", server_url);
    if (isEmpty(userinfo_endpoint)) {
        Logd(TAG, "getUserInfo : could not get endpoint on server : " + server_url);
        return null;
    }

    Logd(TAG, "getUserInfo : " + userinfo_endpoint);
    // build connection
    HttpURLConnection huc = getHUC(userinfo_endpoint);
    huc.setInstanceFollowRedirects(false);
    // huc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

    huc.setRequestProperty("Authorization", "Bearer " + access_token);

    // default result
    String result = null;

    try {
        // try to establish connection 
        huc.connect();
        // get result
        int responseCode = huc.getResponseCode();
        Logd(TAG, "getUserInfo 2 response: " + responseCode);

        // if 200, read http body
        if (responseCode == 200) {
            InputStream is = huc.getInputStream();
            result = convertStreamToString(is);
            is.close();
        }

        // close connection
        huc.disconnect();

    } catch (Exception e) {
        Logd(TAG, "getUserInfo failed");
        e.printStackTrace();
    }

    return result;
}

From source file:honeypot.services.WepawetServiceImpl.java

/**
 * {@inheritDoc}/*from w ww  . j av a 2s. co  m*/
 * @see honeypot.services.WepawetService#checkQueue(java.lang.String)
 */
@Transactional
public void checkQueue(String hash) {
    try {
        String parameters = "resource_type=js&hash=" + URLEncoder.encode(hash, "UTF-8");
        URL url = new URL("http://wepawet.cs.ucsb.edu/services/query.php?" + parameters);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoOutput(true);
        connection.setRequestMethod("GET");

        //Send request
        connection.connect();
        if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
            InputStream is = connection.getInputStream();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            int data;
            while ((data = is.read()) != -1) {
                os.write(data);
            }
            is.close();
            // Process the XML message.
            handleQueryMsg(new ByteArrayInputStream(os.toByteArray()), hash);
            os.close();
        }
        connection.disconnect();
    } catch (final Exception e) {
        log.error("Exception occured querying the hash.", e);
        WepawetError wepawetError = new WepawetError();
        wepawetError.setCode("-1");
        wepawetError.setMessage(e.getMessage());
        wepawetError.setCreated(new Date());
        // Save the error to the database.
        entityManager.persist(wepawetError);
    }

}

From source file:br.com.ufc.palestrasufc.twitter.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * /*from   w w  w .j  a  va 2s  . c o  m*/
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 * 
 * @param url - the resource to open: must be a welformed URL
 * @param method - the HTTP method to use ("GET", "POST", etc.)
 * @param params - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Log.d("Twitter-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " TwitterAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).getBytes());

            }
        }
        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}