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:jfix.util.Urls.java

/**
 * Returns content from given url as string. The url can contain
 * username:password after the protocol, so that basic authorization is
 * possible./*from  w  w  w.  ja  v  a2 s .c o m*/
 * 
 * Example for url with basic authorization:
 * 
 * http://username:password@www.domain.org/index.html
 */
public static String readString(String url, int timeout) {
    Reader reader = null;
    try {
        URLConnection uc = new URL(url).openConnection();
        if (uc instanceof HttpURLConnection) {
            HttpURLConnection httpConnection = (HttpURLConnection) uc;
            httpConnection.setConnectTimeout(timeout * 1000);
            httpConnection.setReadTimeout(timeout * 1000);
        }
        Matcher matcher = Pattern.compile("://(\\w+:\\w+)@").matcher(url);
        if (matcher.find()) {
            String auth = matcher.group(1);
            String encoding = Base64.getEncoder().encodeToString(auth.getBytes());
            uc.setRequestProperty("Authorization", "Basic " + encoding);
        }
        String charset = (uc.getContentType() != null && uc.getContentType().contains("charset="))
                ? uc.getContentType().split("charset=")[1]
                : "utf-8";
        reader = new BufferedReader(new InputStreamReader(uc.getInputStream(), charset));
        StringBuilder sb = new StringBuilder();
        for (int chr; (chr = reader.read()) != -1;) {
            sb.append((char) chr);
        }
        return sb.toString();
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    }
}

From source file:com.nit.vicky.web.HttpFetcher.java

public static String downloadFileToSdCardMethod(String UrlToFile, Context context, String prefix, String method,
        Boolean isMP3) {//w w w .ja  v  a  2s  . c  om
    try {
        URL url = new URL(UrlToFile);

        String extension = ".mp3";

        if (!isMP3)
            extension = UrlToFile.substring(UrlToFile.lastIndexOf("."));

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(10 * 1000);
        urlConnection.setReadTimeout(10 * 1000);
        urlConnection.setRequestMethod(method);
        //urlConnection.setRequestProperty("Referer", "http://mm.taobao.com/");
        urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
        urlConnection.setRequestProperty("Accept", "*/*");
        urlConnection.connect();

        File file = File.createTempFile(prefix, extension, DiskUtil.getStoringDirectory());

        FileOutputStream fileOutput = new FileOutputStream(file);
        InputStream inputStream = urlConnection.getInputStream();

        byte[] buffer = new byte[1024];
        int bufferLength = 0;

        while ((bufferLength = inputStream.read(buffer)) > 0) {
            fileOutput.write(buffer, 0, bufferLength);
        }
        fileOutput.close();

        return file.getAbsolutePath();

    } catch (Exception e) {
        return "FAILED " + e.getMessage();
    }
}

From source file:localSPs.SpiderOakAPI.java

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

    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;
}

From source file:Main.java

public static boolean hasActiveInternetConnection(Context context) {
    if (isNetworkAvailable(context)) {
        try {//  ww  w .  j  a  v  a2  s  .c om
            HttpURLConnection connection = (HttpURLConnection) (new URL(
                    "http://clients3.google.com/generate_204")).openConnection();
            connection.setRequestProperty("User-Agent", "Test");
            connection.setRequestProperty("Connection", "close");
            connection.setReadTimeout(1500);
            connection.connect();
            return (connection.getResponseCode() == 204 && connection.getContentLength() == 0);
        } catch (IOException e) {
            Log.e("ERROR", "Error checking internet connection");
        }
    } else
        Log.e("ERROR", "No network available");
    return false;
}

From source file:Main.java

public static String getHtml(String getUrl, String charsetName) {
    String html = "";
    URL url;//  w  ww. j  av  a 2  s. com
    try {
        url = new URL(getUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("User-Agent", userAgent);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Cache-Control", "no-cache");
        connection.setReadTimeout(timeout);
        connection.setFollowRedirects(true);
        connection.connect();
        InputStream inStrm = connection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(inStrm, charsetName));
        String temp = "";

        while ((temp = br.readLine()) != null) {
            html = html + (temp + '\n');
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return html;
}

From source file:com.ibuildapp.romanblack.CataloguePlugin.imageloader.Utils.java

public static String downloadFile(Context context, String url, String md5) {
    final int BYTE_ARRAY_SIZE = 8024;
    final int CONNECTION_TIMEOUT = 30000;
    final int READ_TIMEOUT = 30000;

    try {/*from w w w.j a va2s  .  c om*/
        for (int i = 0; i < 3; i++) {
            URL fileUrl = new URL(URLDecoder.decode(url));
            HttpURLConnection connection = (HttpURLConnection) fileUrl.openConnection();
            connection.setConnectTimeout(CONNECTION_TIMEOUT);
            connection.setReadTimeout(READ_TIMEOUT);
            connection.connect();

            int status = connection.getResponseCode();

            if (status >= HttpStatus.SC_BAD_REQUEST) {
                connection.disconnect();

                continue;
            }

            BufferedInputStream bufferedInputStream = new BufferedInputStream(connection.getInputStream());
            File file = new File(StaticData.getCachePath(context) + md5);

            if (!file.exists()) {
                new File(StaticData.getCachePath(context)).mkdirs();
                file.createNewFile();
            }

            FileOutputStream fileOutputStream = new FileOutputStream(file, false);
            int byteCount;
            byte[] buffer = new byte[BYTE_ARRAY_SIZE];

            while ((byteCount = bufferedInputStream.read(buffer, 0, BYTE_ARRAY_SIZE)) != -1)
                fileOutputStream.write(buffer, 0, byteCount);

            bufferedInputStream.close();
            fileOutputStream.flush();
            fileOutputStream.close();

            return file.getAbsolutePath();
        }
    } catch (Exception e) {
        e.printStackTrace();

        return null;
    }

    return null;
}

From source file:com.melniqw.instagramsdk.Network.java

private static String sendDummyRequest(String url, String body, Request request) throws IOException {
    HttpURLConnection connection = null;
    try {/*from   ww  w  .j  ava2  s .c o m*/
        connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(10000);
        connection.setUseCaches(false);
        connection.setDoInput(true);
        //            connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
        if (request == Request.GET) {
            connection.setDoOutput(false);
            connection.setRequestMethod("GET");
        } else if (request == Request.POST) {
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
        }
        if (REQUEST_ENABLE_COMPRESSION)
            connection.setRequestProperty("Accept-Encoding", "gzip");
        if (request == Request.POST)
            connection.getOutputStream().write(body.getBytes("utf-8"));
        int code = connection.getResponseCode();
        System.out.println(TAG + " responseCode = " + code);
        //It may happen due to keep-alive problem http://stackoverflow.com/questions/1440957/httpurlconnection-getresponsecode-returns-1-on-second-invocation
        if (code == -1)
            throw new WrongResponseCodeException("Network error");
        // ?    200
        //on error can also read error stream from connection.
        InputStream inputStream = new BufferedInputStream(connection.getInputStream(), 8192);
        String encoding = connection.getHeaderField("Content-Encoding");
        if (encoding != null && encoding.equalsIgnoreCase("gzip"))
            inputStream = new GZIPInputStream(inputStream);
        String response = Utils.convertStreamToString(inputStream);
        System.out.println(TAG + " response = " + response);
        return response;
    } finally {
        if (connection != null)
            connection.disconnect();
    }
}

From source file:com.example.android.didyoufeelit.Utils.java

/**
 * Make an HTTP request to the given URL and return a String as the response.
 *///from   w  ww  . j  a v  a  2 s.c o  m
private static String makeHttpRequest(URL url) throws IOException {
    String jsonResponse = "";

    // If the URL is null, then return early.
    if (url == null) {
        return jsonResponse;
    }

    HttpURLConnection urlConnection = null;
    InputStream inputStream = null;
    try {
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setReadTimeout(10000 /* milliseconds */);
        urlConnection.setConnectTimeout(15000 /* milliseconds */);
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        // If the request was successful (response code 200),
        // then read the input stream and parse the response.
        if (urlConnection.getResponseCode() == 200) {
            inputStream = urlConnection.getInputStream();
            jsonResponse = readFromStream(inputStream);
        } else {
            Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (inputStream != null) {
            inputStream.close();
        }
    }
    return jsonResponse;
}

From source file:com.intellij.lang.jsgraphql.languageservice.JSGraphQLNodeLanguageServiceClient.java

private static <R> R executeRequest(Request request, Class<R> responseClass, @NotNull Project project,
        boolean setProjectDir) {

    URL url = getJSGraphQLNodeLanguageServiceInstance(project, setProjectDir);
    if (url == null) {
        return null;
    }//from   w w  w.  j av  a  2  s .  co  m
    HttpURLConnection httpConnection = null;
    try {
        httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setConnectTimeout(50);
        httpConnection.setReadTimeout(1000);
        httpConnection.setRequestMethod("POST");
        httpConnection.setDoOutput(true);
        httpConnection.setRequestProperty("Content-Type", "application/json");
        httpConnection.connect();
        try (OutputStreamWriter writer = new OutputStreamWriter(httpConnection.getOutputStream())) {
            final String jsonRequest = new Gson().toJson(request);
            writer.write(jsonRequest);
            writer.flush();
            writer.close();
        }
        if (httpConnection.getResponseCode() == 200) {
            if (responseClass == null) {
                return null;
            }
            try (InputStream inputStream = httpConnection.getInputStream()) {
                String jsonResponse = IOUtils.toString(inputStream, "UTF-8");
                R response = new Gson().fromJson(jsonResponse, responseClass);
                return response;
            }
        } else {
            log.warn("Got error from JS GraphQL Language Service: HTTP " + httpConnection.getResponseCode()
                    + ": " + httpConnection.getResponseMessage());
        }
    } catch (IOException e) {
        log.warn("Unable to connect to dev server", e);
    } finally {
        if (httpConnection != null) {
            httpConnection.disconnect();
        }
    }
    return null;
}

From source file:net.daporkchop.porkselfbot.util.HTTPUtils.java

public static HttpURLConnection createUrlConnection(final URL url) throws IOException {
    Validate.notNull(url);//from   ww  w.j av  a2 s  . com
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setConnectTimeout(15000);
    connection.setReadTimeout(15000);
    connection.setUseCaches(false);
    return connection;
}