Example usage for java.net HttpURLConnection setConnectTimeout

List of usage examples for java.net HttpURLConnection setConnectTimeout

Introduction

In this page you can find the example usage for java.net HttpURLConnection setConnectTimeout.

Prototype

public void setConnectTimeout(int timeout) 

Source Link

Document

Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced by this URLConnection.

Usage

From source file:org.overlord.sramp.governance.shell.commands.Pkg2SrampCommand.java

/**
 * Returns true if the given URL can be accessed.
 * @param checkUrl//from  w ww .java 2 s.c om
 * @param user
 * @param password
 */
public boolean urlExists(String checkUrl, String user, String password) {
    try {
        URL checkURL = new URL(checkUrl);
        HttpURLConnection checkConnection = (HttpURLConnection) checkURL.openConnection();
        checkConnection.setRequestMethod("GET"); //$NON-NLS-1$
        checkConnection.setRequestProperty("Accept", "application/xml"); //$NON-NLS-1$ //$NON-NLS-2$
        checkConnection.setConnectTimeout(10000);
        checkConnection.setReadTimeout(10000);
        applyAuth(checkConnection, user, password);
        checkConnection.connect();
        return (checkConnection.getResponseCode() == 200);
    } catch (Exception e) {
        return false;
    }
}

From source file:com.rapleaf.api.personalization.RapleafApi.java

protected String bulkJsonResponse(String urlStr, String list) throws Exception {
    URL url = new URL(urlStr);
    HttpURLConnection handle = (HttpURLConnection) url.openConnection();
    handle.setRequestProperty("User-Agent", getUserAgent());
    handle.setRequestProperty("Content-Type", "application/json");
    handle.setConnectTimeout(timeout);
    handle.setReadTimeout(bulkTimeout);/*  w w  w .j ava2  s .com*/
    handle.setDoOutput(true);
    handle.setRequestMethod("POST");
    OutputStreamWriter wr = new OutputStreamWriter(handle.getOutputStream());
    wr.write(list);
    wr.flush();
    BufferedReader rd = new BufferedReader(new InputStreamReader(handle.getInputStream()));
    String line = rd.readLine();
    StringBuilder sb = new StringBuilder();
    while (line != null) {
        sb.append(line);
        line = rd.readLine();
    }
    wr.close();
    rd.close();

    int responseCode = handle.getResponseCode();
    if (responseCode < 200 || responseCode > 299) {
        throw new Exception("Error Code " + responseCode + ": " + sb.toString());
    }

    return sb.toString();
}

From source file:com.polyvi.xface.extension.advancedfiletransfer.XFileDownloader.java

/**
 * ??(?????/*from  w  ww  .  j  av  a  2  s.  com*/
 * ??????)
 */
private void initDownloadInfo() {
    int totalSize = 0;
    if (isFirst(mUrl)) {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(mUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(TIME_OUT_MILLISECOND);
            connection.setRequestMethod("GET");
            System.getProperties().setProperty("http.nonProxyHosts", url.getHost());
            //cookie?
            setCookieProperty(connection, mUrl);
            if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
                totalSize = connection.getContentLength();
                if (-1 != totalSize) {
                    mDownloadInfo = new XFileDownloadInfo(totalSize, 0, mUrl);
                    // ?mDownloadInfo??
                    mFileTransferRecorder.saveDownloadInfo(mDownloadInfo);
                } else {
                    XLog.e(CLASS_NAME, "cannot get totalSize");
                }
                // temp
                File file = new File(mLocalFilePath + TEMP_FILE_SUFFIX);
                if (file.exists()) {
                    file.delete();
                }
            }
        } catch (IOException e) {
            XLog.e(CLASS_NAME, e.getMessage());
        } finally {
            if (null != connection) {
                connection.disconnect();
            }
        }
    } else {
        // ?url?
        mDownloadInfo = mFileTransferRecorder.getDownloadInfo(mUrl);
        totalSize = mDownloadInfo.getTotalSize();
        mDownloadInfo.setCompleteSize(getCompleteSize(mLocalFilePath + TEMP_FILE_SUFFIX));
    }
    mBufferSize = getSingleTransferLength(totalSize);
}

From source file:com.sample.facebook.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * /*from www  . j a  v a  2 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);
    }
    Log.d("Facebook-Util", method + " URL: " + url);
    //url+="&fields=email";
    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.setConnectTimeout(45000);
        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.attask.api.StreamClient.java

private HttpURLConnection createConnection(String spec, String method) throws IOException {
    URL url = new URL(spec);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    if (conn instanceof HttpsURLConnection) {
        ((HttpsURLConnection) conn).setHostnameVerifier(HOSTNAME_VERIFIER);
    }/*from  ww  w  .ja v a  2  s .  com*/

    conn.setAllowUserInteraction(false);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setConnectTimeout(60000);
    conn.setReadTimeout(300000);
    conn.connect();

    return conn;
}

From source file:com.zhonghui.tool.controller.HttpClient.java

/**
 * get/*from w  w  w  .  j  av  a 2  s . co  m*/
 *
 * @return
 * @throws ProtocolException
 */
private HttpURLConnection createConnectionGet(String encoding) throws ProtocolException {
    HttpURLConnection httpURLConnection = null;
    try {
        httpURLConnection = (HttpURLConnection) url.openConnection();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    httpURLConnection.setConnectTimeout(this.connectionTimeout);// 
    httpURLConnection.setReadTimeout(this.readTimeOut);// ?
    httpURLConnection.setUseCaches(false);// ?
    httpURLConnection.setRequestProperty("Content-type",
            "application/x-www-form-urlencoded;charset=" + encoding);
    httpURLConnection.setRequestMethod("GET");
    return httpURLConnection;
}

From source file:com.google.ytd.picasa.PicasaApiHelper.java

public String getResumableUploadUrl(com.google.ytd.model.PhotoEntry photoEntry, String title,
        String description, String albumId, Double latitude, Double longitude) throws IllegalArgumentException {
    LOG.info(String.format("Resumable upload request.\nTitle: %s\nDescription: %s\nAlbum: %s", title,
            description, albumId));//from   w ww. ja  v  a  2 s . com

    // Picasa API resumable uploads are not currently documented publicly, but they're essentially
    // the same as what YouTube API offers:
    // http://code.google.com/apis/youtube/2.0/developers_guide_protocol_resumable_uploads.html
    // The Java client library does offer support for resumable uploads, but its use of threads
    // and some other assumptions makes it unsuitable for our purposes.
    try {
        URL url = new URL(String.format(RESUMABLE_UPLOADS_URL_FORMAT, albumId));
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setConnectTimeout(CONNECT_TIMEOUT);
        connection.setReadTimeout(READ_TIMEOUT);
        connection.setRequestMethod("POST");

        // Set all the GData request headers. These strings should probably be moved to CONSTANTS.
        connection.setRequestProperty("Content-Type", "application/atom+xml;charset=UTF-8");
        connection.setRequestProperty("Authorization",
                String.format("AuthSub token=\"%s\"", adminConfigDao.getAdminConfig().getPicasaAuthSubToken()));
        connection.setRequestProperty("GData-Version", "2.0");
        connection.setRequestProperty("Slug", photoEntry.getOriginalFileName());
        connection.setRequestProperty("X-Upload-Content-Type", photoEntry.getFormat());
        connection.setRequestProperty("X-Upload-Content-Length",
                String.valueOf(photoEntry.getOriginalFileSize()));

        // If we're given lat/long then create the element to geotag the picture; otherwise, pass in
        // and empty string for no geotag.
        String geoRss = "";
        if (latitude != null && longitude != null) {
            geoRss = String.format(GEO_RSS_XML_FORMAT, latitude, longitude);
            LOG.info("Geo RSS XML: " + geoRss);
        }

        String atomXml = String.format(UPLOAD_ENTRY_XML_FORMAT, StringEscapeUtils.escapeXml(title),
                StringEscapeUtils.escapeXml(description), geoRss);

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(atomXml);
        writer.close();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            String uploadUrl = connection.getHeaderField("Location");
            if (util.isNullOrEmpty(uploadUrl)) {
                throw new IllegalArgumentException("No Location header found in HTTP response.");
            } else {
                LOG.info("Resumable upload URL is " + uploadUrl);

                return uploadUrl;
            }
        } else {
            LOG.warning(String.format("HTTP POST to %s returned status %d (%s).", url.toString(),
                    connection.getResponseCode(), connection.getResponseMessage()));
        }
    } catch (MalformedURLException e) {
        LOG.log(Level.WARNING, "", e);

        throw new IllegalArgumentException(e);
    } catch (IOException e) {
        LOG.log(Level.WARNING, "", e);
    }

    return null;
}

From source file:com.zhonghui.tool.controller.HttpClient.java

/**
 * Post/*  w  w  w . j  a va 2 s  .  c o m*/
 *
 * @return
 * @throws ProtocolException
 */
private HttpURLConnection createConnection(String encoding) throws ProtocolException {
    HttpURLConnection httpURLConnection = null;
    try {
        httpURLConnection = (HttpURLConnection) url.openConnection();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    httpURLConnection.setConnectTimeout(this.connectionTimeout);// 
    httpURLConnection.setReadTimeout(this.readTimeOut);// ?
    httpURLConnection.setDoInput(true); // ? post?
    httpURLConnection.setDoOutput(true); // ? post?
    httpURLConnection.setUseCaches(false);// ?
    httpURLConnection.setRequestProperty("Content-type",
            "application/x-www-form-urlencoded;charset=" + encoding);
    httpURLConnection.setRequestMethod("POST");
    return httpURLConnection;
}

From source file:foam.starwisp.NetworkManager.java

private void Request(String u, String type, String CallbackName) {
    try {/* ww  w  .  j av a 2  s .  c  om*/
        Log.i("starwisp", "pinging: " + u);
        URL url = new URL(u);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        con.setUseCaches(false);
        con.setReadTimeout(100000 /* milliseconds */);
        con.setConnectTimeout(150000 /* milliseconds */);
        con.setRequestMethod("GET");
        con.setDoInput(true);
        // Starts the query
        con.connect();
        m_RequestHandler.sendMessage(
                Message.obtain(m_RequestHandler, 0, new ReqMsg(con.getInputStream(), type, CallbackName)));

    } catch (Exception e) {
        Log.i("starwisp", e.toString());
        e.printStackTrace();
    }
}

From source file:com.jaspersoft.jasperserver.api.engine.jasperreports.util.AwsEc2MetadataClient.java

private String readResource(String resourcePath) {
    HttpURLConnection connection = null;
    URL url = null;/*from  w ww  .  ja  va2s.c  o m*/
    try {
        url = getEc2MetadataServiceUrlForResource(resourcePath);
        log.debug("Connecting to EC2 instance metadata service at URL: " + url.toString());
        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(SECOND * 2);
        connection.setReadTimeout(SECOND * 7);
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.connect();

        if (connection.getResponseCode() >= HttpURLConnection.HTTP_OK
                && connection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
            return readResponse(connection);
        } else {
            return null;
        }
    } catch (Exception e) {
        return null;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}