Example usage for java.net HttpURLConnection setReadTimeout

List of usage examples for java.net HttpURLConnection setReadTimeout

Introduction

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

Prototype

public void setReadTimeout(int timeout) 

Source Link

Document

Sets the read timeout to a specified timeout, in milliseconds.

Usage

From source file:com.blogspot.ryanfx.auth.GoogleUtil.java

/**
 * Sends the auth token to google and gets the json result.
 * @param token auth token/*from  ww w  . j ava 2s  . c  o m*/
 * @return json result if valid request, null if invalid.
 * @throws IOException
 * @throws LoginException
 */
private static String issueTokenGetRequest(String token) throws IOException, LoginException {
    int timeout = 2000;
    URL u = new URL("https://www.googleapis.com/oauth2/v2/userinfo");
    HttpURLConnection c = (HttpURLConnection) u.openConnection();
    c.setRequestMethod("GET");
    c.setRequestProperty("Content-length", "0");
    c.setRequestProperty("Authorization", "OAuth " + token);
    c.setUseCaches(false);
    c.setAllowUserInteraction(false);
    c.setConnectTimeout(timeout);
    c.setReadTimeout(timeout);
    c.connect();
    int status = c.getResponseCode();
    if (status == HttpServletResponse.SC_OK) {
        BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();
        return sb.toString();
    } else if (status == HttpServletResponse.SC_UNAUTHORIZED) {
        Logger.getLogger(GoogleUtil.class.getName()).severe("Invalid token request: " + token);
    }
    return null;
}

From source file:com.consumerkarma.TTS.SpeechAuth.java

/**
 * Sets up an OAuth client credentials authentication.
 * Follow this with a call to fetchTo() to actually load the data.
 * @param oauthService the URL of the OAuth client credentials service
 * @param apiKey the OAuth client ID/*from  ww  w . j  av a2  s  .  co m*/
 * @param apiSecret the OAuth client secret
 * @throws IllegalArgumentException for bad URL, etc.
**/
public static SpeechAuth forService(String oauthService, String apiKey, String apiSecret)
        throws IllegalArgumentException {
    try {
        URL url = new URL(oauthService);
        HttpURLConnection request = (HttpURLConnection) url.openConnection();
        String data = String.format(Locale.US, OAUTH_DATA, apiKey, apiSecret);
        byte[] bytes = data.getBytes("UTF8");
        request.setConnectTimeout(CONNECT_TIMEOUT);
        request.setReadTimeout(READ_TIMEOUT);
        return new SpeechAuth(request, bytes);
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    } catch (ClassCastException e) {
        throw new IllegalArgumentException("URL must be HTTP: " + oauthService, e);
    }
}

From source file:com.androidzeitgeist.dashwatch.common.IOUtil.java

static String fetchPlainText(URL url) throws IOException {
    InputStream in = null;/*ww  w.j  av a  2  s  . c  o m*/

    try {
        OkHttpClient client = new OkHttpClient();
        HttpURLConnection conn = client.open(url);
        conn.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
        conn.setReadTimeout(DEFAULT_READ_TIMEOUT);
        in = conn.getInputStream();
        return readFullyPlainText(in);

    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:com.mnt.base.util.HttpUtil.java

private static void setTimeout(HttpURLConnection conn) {
    if (connectionTimeout > 0) {
        conn.setConnectTimeout(connectionTimeout);
    }/*from  w  w  w . j  ava  2 s.  c om*/

    if (readTimeout > 0) {
        conn.setReadTimeout(readTimeout);
    }
}

From source file:net.kourlas.voipms_sms.Utils.java

/**
 * Retrieves a JSON object from the specified URL.
 * <p/>/* w w w  . j a v  a2  s  . c  o m*/
 * Note that this is a blocking method; it should not be called from the URI thread.
 *
 * @param urlString The URL to retrieve the JSON from.
 * @return The JSON object at the specified URL.
 * @throws IOException   if a connection to the server could not be established.
 * @throws JSONException if the server did not return valid JSON.
 */
public static JSONObject getJson(String urlString) throws IOException, JSONException {
    URL url = new URL(urlString);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setReadTimeout(10000);
    connection.setConnectTimeout(15000);
    connection.setRequestMethod("GET");
    connection.setDoInput(true);
    connection.connect();

    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
    StringBuilder data = new StringBuilder();
    String newLine = System.getProperty("line.separator");
    String line;
    while ((line = reader.readLine()) != null) {
        data.append(line);
        data.append(newLine);
    }
    reader.close();

    return new JSONObject(data.toString());
}

From source file:Main.java

public static void downloadImage(String imageUrl) {
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        Log.d("TAG", "monted sdcard");
    } else {//from  w  ww .  ja v a2 s  .c  o m
        Log.d("TAG", "has no sdcard");
    }
    HttpURLConnection con = null;
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    BufferedInputStream bis = null;
    File imageFile = null;
    try {
        URL url = new URL(imageUrl);
        con = (HttpURLConnection) url.openConnection();
        con.setConnectTimeout(5 * 1000);
        con.setReadTimeout(15 * 1000);
        con.setDoInput(true);
        con.setDoOutput(true);
        bis = new BufferedInputStream(con.getInputStream());
        imageFile = new File(getImagePath(imageUrl));
        fos = new FileOutputStream(imageFile);
        bos = new BufferedOutputStream(fos);
        byte[] b = new byte[1024];
        int length;
        while ((length = bis.read(b)) != -1) {
            bos.write(b, 0, length);
            bos.flush();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
            if (con != null) {
                con.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (imageFile != null) {
    }
}

From source file:de.jetwick.util.Translate.java

public static String download(String urlAsString) {
    try {//from ww w  .j  av  a 2s. c om
        URL url = new URL(urlAsString);
        //using proxy may increase latency
        HttpURLConnection hConn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
        hConn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (X11; Linux i686; rv:7.0.1) Gecko/20100101 Firefox/7.0.1");
        hConn.addRequestProperty("Referer", "http://jetsli.de/crawler");

        hConn.setConnectTimeout(2000);
        hConn.setReadTimeout(2000);
        InputStream is = hConn.getInputStream();
        if ("gzip".equals(hConn.getContentEncoding()))
            is = new GZIPInputStream(is);

        return getInputStream(is);
    } catch (Exception ex) {
        return "";
    }
}

From source file:com.att.ads.sample.SpeechAuth.java

/**
 * Sets up an OAuth client credentials authentication.
 * Follow this with a call to fetchTo() to actually load the data.
 * @param oauthService the URL of the OAuth client credentials service
 * @param apiKey the OAuth client ID//from ww  w .  j a  va  2s. c o  m
 * @param apiSecret the OAuth client secret
 * @throws IllegalArgumentException for bad URL, etc.
**/
public static SpeechAuth forService(String oauthService, String oauthScope, String apiKey, String apiSecret)
        throws IllegalArgumentException {
    try {
        URL url = new URL(oauthService);
        HttpURLConnection request = (HttpURLConnection) url.openConnection();
        String data = String.format(Locale.US, OAUTH_DATA, oauthScope, apiKey, apiSecret);
        byte[] bytes = data.getBytes("UTF8");
        request.setConnectTimeout(CONNECT_TIMEOUT);
        request.setReadTimeout(READ_TIMEOUT);
        return new SpeechAuth(request, bytes);
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    } catch (ClassCastException e) {
        throw new IllegalArgumentException("URL must be HTTP: " + oauthService, e);
    }
}

From source file:ee.ria.xroad.common.util.CertHashBasedOcspResponderClient.java

/**
 * Creates a GET request to the internal cert hash based OCSP responder and expects OCSP responses.
 *
 * @param destination URL of the OCSP response provider
 * @return list of OCSP response objects
 * @throws IOException   if I/O errors occurred
 * @throws OCSPException if the response could not be parsed
 *///from www  . ja  v  a  2  s.c o m
public static List<OCSPResp> getOcspResponsesFromServer(URL destination) throws IOException, OCSPException {
    HttpURLConnection connection = (HttpURLConnection) destination.openConnection();
    connection.setRequestProperty("Accept", MimeTypes.MULTIPART_RELATED);
    connection.setDoOutput(true);
    connection.setConnectTimeout(SystemProperties.getOcspResponderClientConnectTimeout());
    connection.setReadTimeout(SystemProperties.getOcspResponderClientReadTimeout());
    connection.setRequestMethod(METHOD);
    connection.connect();

    if (!VALID_RESPONSE_CODES.contains(connection.getResponseCode())) {
        log.error("Invalid HTTP response ({}) from responder: {}", connection.getResponseCode(),
                connection.getResponseMessage());

        throw new IOException(connection.getResponseMessage());
    }

    MimeConfig config = new MimeConfig.Builder().setHeadlessParsing(connection.getContentType()).build();

    final List<OCSPResp> responses = new ArrayList<>();
    final MimeStreamParser parser = new MimeStreamParser(config);

    parser.setContentHandler(new AbstractContentHandler() {
        @Override
        public void startMultipart(BodyDescriptor bd) {
            parser.setFlat();
        }

        @Override
        public void body(BodyDescriptor bd, InputStream is) throws MimeException, IOException {
            if (bd.getMimeType().equalsIgnoreCase(MimeTypes.OCSP_RESPONSE)) {
                responses.add(new OCSPResp(IOUtils.toByteArray(is)));
            }
        }
    });

    try {
        parser.parse(connection.getInputStream());
    } catch (MimeException e) {
        throw new OCSPException("Error parsing response", e);
    }

    return responses;
}

From source file:oneDrive.OneDriveAPI.java

public static String connectWithREST(String url, String method) throws IOException, ProtocolException {
    String newURL = "";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    // Connect with a REST Method: GET, DELETE, PUT
    con.setRequestMethod(method);/*from   w w  w .  j  ava 2 s  .co  m*/
    //add request header
    con.setReadTimeout(20000);
    con.setConnectTimeout(20000);
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    if (method.equals(DELETE) || method.equals(PUT) || getSize)
        con.addRequestProperty("Authorization", "Bearer " + ACCESS_TOKEN);

    int responseCode = con.getResponseCode();
    // Read response
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    newURL = response.toString();

    return newURL;
}