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.epic.framework.implementation.tapjoy.TapjoyURLConnection.java

/**
 * Performs a network request call to the specified URL and parameters.
 * /*from   www  .ja v  a 2  s  . c om*/
 * @param url                     The base URL.
 * @param params                  The URL parameters.
 * @return                         Response from the server.
 */
public String connectToURL(String url, String params) {
    String httpResponse = null;

    BufferedReader rd = null;
    StringBuilder sb = null;
    String line = null;

    try {
        String requestURL = url + params;

        // Replaces all spaces.
        requestURL = requestURL.replaceAll(" ", "%20");

        TapjoyLog.i(TAPJOY_URL_CONNECTION, "baseURL: " + url);
        TapjoyLog.i(TAPJOY_URL_CONNECTION, "requestURL: " + requestURL);

        // USE java.net HTTP connection instead.

        URL httpURL = new URL(requestURL);
        HttpURLConnection connection = (HttpURLConnection) httpURL.openConnection();
        connection.setConnectTimeout(15000);
        connection.setReadTimeout(30000);
        httpResponse = connection.getResponseMessage();

        connection.connect();

        // Read the result from the server.
        rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        sb = new StringBuilder();

        while ((line = rd.readLine()) != null) {
            sb.append(line + '\n');
        }

        httpResponse = sb.toString();

        // OLD CODE USING APACHE API

        // HttpGet http = new HttpGet(requestURL);
        //
        // // Create a HttpParams object so we can set our timeout times.
        // HttpParams httpParameters = new BasicHttpParams();
        //
        // // Time to wait to establish initial connection.
        // HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
        //
        // // Time to wait for incoming data.
        // HttpConnectionParams.setSoTimeout(httpParameters, 30000);
        //
        // // Create a http client with out timeout settings.
        // HttpClient client = new DefaultHttpClient(httpParameters);
        //
        // HttpResponse response = client.execute(http);
        // HttpEntity entity = response.getEntity();
        //
        // httpResponse = EntityUtils.toString(entity);

        TapjoyLog.i(TAPJOY_URL_CONNECTION, "--------------------");
        // TapjoyLog.i(TAPJOY_URL_CONNECTION, "response status: " + response.getStatusLine().getStatusCode());
        TapjoyLog.i(TAPJOY_URL_CONNECTION, "response size: " + httpResponse.length());
        TapjoyLog.i(TAPJOY_URL_CONNECTION, "response: ");
        TapjoyLog.i(TAPJOY_URL_CONNECTION, "" + httpResponse);
        TapjoyLog.i(TAPJOY_URL_CONNECTION, "--------------------");
    } catch (Exception e) {
        TapjoyLog.e(TAPJOY_URL_CONNECTION, "Exception: " + e.toString());
    }

    return httpResponse;
}

From source file:com.facebook.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//w  w  w .ja  v a2  s .  c o  m
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
@SuppressWarnings("deprecation")
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("Facebook-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
    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.bpd.facebook.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  www .ja v  a  2s .co  m
 * @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;

    // Try to get filename key
    String filename = params.getString("filename");

    // If found
    if (filename != null) {
        // Remove from params
        params.remove("filename");
    }

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Log.d("Facebook-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
    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=\"" + ((filename != null) ? 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:UrlEngine.java

@Override
public ResponseEntity<String> submit(JCurlRequestOptions requestOptions) throws Exception {
    System.setProperty("http.keepAlive", "true");

    ResponseEntity<String> responseEntity = null;
    URL obj = new URL(requestOptions.getUrl());

    for (int i = 0; i < requestOptions.getCount(); i++) {
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // add request header
        con.setRequestMethod("GET");
        con.setConnectTimeout(2000);//from w  w w .j a v a2s  . c o m
        for (Map.Entry<String, String> e : requestOptions.getHeaderMap().entrySet()) {
            con.setRequestProperty(e.getKey(), e.getValue());
        }

        System.out.println("\nSending 'GET' request to URL : " + requestOptions.getUrl());
        con.connect();

        int responseCode = con.getResponseCode();
        System.out.println("Response Code : " + responseCode);

        final InputStream is = con.getInputStream();
        String response = IOUtils.toString(is);
        is.close();

        //print result
        System.out.println(response);

        responseEntity = new ResponseEntity<String>(response, HttpStatus.valueOf(responseCode));
    }
    return responseEntity;
}

From source file:com.entertailion.android.dial.HttpRequestHelper.java

public InputStream getHttpStream(String urlString) throws IOException {
    InputStream in = null;//  w  w w  .j  a  v a  2 s. c o  m
    int response = -1;

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();

    if (!(conn instanceof HttpURLConnection))
        throw new IOException("Not an HTTP connection");

    try {
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();

        response = httpConn.getResponseCode();

        if (response == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();
        }
    } catch (Exception e) {
        throw new IOException("Error connecting");
    } // end try-catch

    return in;
}

From source file:com.github.bmadecoder.Authenticator.java

public long getTimeDiff() {
    if (!this.syncing) {
        return 0;
    }// w  ww. java  2 s.  c  om
    try {
        URL url = URI.create("http://m.eu.mobileservice.blizzard.com/enrollment/time.htm").toURL();
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-type", "application/octet-stream");
        conn.setRequestProperty("Accept", "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2");
        conn.setReadTimeout(10000);
        conn.setDoInput(true);
        conn.connect();

        byte[] servertime = new byte[8];
        InputStream connectionStream = conn.getInputStream();
        connectionStream.read(servertime, 0, 8);
        connectionStream.close();
        conn.disconnect();

        return new BigInteger(servertime).longValue() - System.currentTimeMillis();
    } catch (MalformedURLException e) {
        throw new IllegalStateException(e);
    } catch (IOException e) {
        return 0;
    }
}

From source file:com.mobile.godot.core.service.task.GodotAction.java

@Override
public void run() {

    System.out.println("inside runnable");

    android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);

    URL url = GodotURLUtils.parseToURL(this.mServlet, this.mParams);

    System.out.println("url: " + url);

    HttpURLConnection connection = null;
    InputStream iStream;/*  w w w .ja v a 2s .  c  o  m*/
    InputStream eStream;
    int responseCode = 0;
    String data = null;

    try {

        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.connect();

        if (!url.getHost().equals(connection.getURL().getHost())) {
            this.mHandler.obtainMessage(GodotMessage.Error.REDIRECTION_ERROR).sendToTarget();
            connection.disconnect();
            return;
        }

        try {

            iStream = new BufferedInputStream(connection.getInputStream());
            BufferedReader bReader = new BufferedReader(new InputStreamReader(iStream));
            data = bReader.readLine();
            responseCode = connection.getResponseCode();

        } catch (IOException exc) {

            eStream = new BufferedInputStream(connection.getErrorStream());
            BufferedReader bReader = new BufferedReader(new InputStreamReader(eStream));
            data = bReader.readLine();
            responseCode = connection.getResponseCode();

        } finally {

            if (data != null) {

                this.mHandler.obtainMessage(this.mMessageMap.get(responseCode), data).sendToTarget();

            } else {

                this.mHandler.obtainMessage(this.mMessageMap.get(responseCode)).sendToTarget();

            }
        }

    } catch (IOException exc) {

        this.mHandler.obtainMessage(GodotMessage.Error.SERVER_ERROR).sendToTarget();

    } finally {

        connection.disconnect();

    }

}

From source file:com.shinymayhem.radiopresets.ServiceAudioFormat.java

private Map<String, List<String>> getInputStream(String url) throws IOException, StreamHttpException {
    /*//from   w  ww .ja va2 s .c o m
    URL streamUrl = new URL(url);
    StreamURLConnection con;
    con = (StreamURLConnection)streamUrl.openConnection();
    con.setRequestProperty("Connection", "close");
    con.connect();
    int responseCode = con.getResponseCode(); 
    if (responseCode < 200 || responseCode >= 300)
    {
    this.handleHttpError(con);
    }*/
    URL streamUrl = new URL(url);
    HttpURLConnection con;
    con = (HttpURLConnection) streamUrl.openConnection();
    con.setRequestProperty("Connection", "close");
    con.connect();
    Map<String, List<String>> headers = con.getHeaderFields();
    String statusLine = headers.get(null).get(0); //con.getHeaderField(0);
    //String statusLine2 = con.getHeaderField(0);
    String message = statusLine;
    int responseCode = -1;
    if (statusLine.startsWith("HTTP/1.") || statusLine.startsWith("ICY")) {
        int codePos = statusLine.indexOf(' ');
        if (codePos > 0) {

            int phrasePos = statusLine.indexOf(' ', codePos + 1);
            if (phrasePos > 0 && phrasePos < statusLine.length()) {
                message = statusLine.substring(phrasePos + 1);
            }

            if (phrasePos < 0)
                phrasePos = statusLine.length();

            try {
                responseCode = Integer.parseInt(statusLine.substring(codePos + 1, phrasePos));
            } catch (NumberFormatException e) {
            }
        }
    }

    this.handleHttpResponse(responseCode, message);
    mStream = con.getInputStream();
    return headers;
}

From source file:org.apache.mycat.advisor.common.net.http.HttpService.java

/**
 * ? header?//from  w  w  w.j  a  v  a  2s  . co m
 *
 * @param requestUrl
 * @param requestMethod
 * @param WithTokenHeader
 * @param token
 * @return
 */
public static String doHttpRequest(String requestUrl, String requestMethod, Boolean WithTokenHeader,
        String token) {
    String result = null;
    InetAddress ipaddr;
    int responseCode = -1;
    try {
        ipaddr = InetAddress.getLocalHost();
        StringBuffer buffer = new StringBuffer();
        URL url = new URL(requestUrl);
        HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
        httpUrlConn.setDoOutput(true);
        httpUrlConn.setDoInput(true);
        httpUrlConn.setUseCaches(false);

        httpUrlConn.setUseCaches(false);
        httpUrlConn.setRequestProperty("Accept-Charset", DEFAULT_CHARSET);
        httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=" + DEFAULT_CHARSET);
        if (WithTokenHeader) {
            if (token == null) {
                throw new IllegalStateException("Oauth2 token is not set!");
            }
            httpUrlConn.setRequestProperty("Authorization", "OAuth2 " + token);
            httpUrlConn.setRequestProperty("API-RemoteIP", ipaddr.getHostAddress());
        }
        // ?GET/POST
        httpUrlConn.setRequestMethod(requestMethod);

        if ("GET".equalsIgnoreCase(requestMethod))
            httpUrlConn.connect();

        //            // ????
        //            if (null != outputJson) {
        //                OutputStream outputStream = httpUrlConn.getOutputStream();
        //                //??
        //                outputStream.write(outputJson.getBytes(DEFAULT_CHARSET));
        //                outputStream.close();
        //            }

        // ???
        InputStream inputStream = httpUrlConn.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, DEFAULT_CHARSET);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }
        result = buffer.toString();
        bufferedReader.close();
        inputStreamReader.close();
        // ?
        inputStream.close();
        httpUrlConn.disconnect();
    } catch (ConnectException ce) {
        logger.error("server connection timed out.", ce);
    } catch (Exception e) {
        logger.error("http request error:", e);
    } finally {
        return result;
    }
}

From source file:com.facebook.android.library.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * /*from w  w w  . j  av  a2  s  . 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);
    }
    Util.logd("Facebook-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.get(key) instanceof byte[]) {
                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;
}