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.roadwarrior.vtiger.client.NetworkUtilities.java

/**
 * Fetches the list of friend data updates from the server
 * /*from   w w w. j ava 2  s .  c  o  m*/
 * @param account The account being synced.
 * @param authtoken The authtoken stored in AccountManager for this account
 * @param lastUpdated The last time that sync was performed
 * @return list The list of updates received from the server.
 */
public static List<User> fetchFriendUpdates(Account account, String auth_url, String authtoken,
        long serverSyncState/*Date lastUpdated*/, String type_contact)
        throws JSONException, ParseException, IOException, AuthenticationException {
    ArrayList<User> friendList = new ArrayList<User>();
    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(PARAM_OPERATION, "sync"));
    params.add(new BasicNameValuePair(PARAM_SESSIONNAME, sessionName));
    if (serverSyncState == 0)
        params.add(new BasicNameValuePair("modifiedTime", "878925701")); // il y a 14 ans.... 
    else
        params.add(new BasicNameValuePair("modifiedTime", String.valueOf(serverSyncState)));
    params.add(new BasicNameValuePair("elementType", type_contact)); // "Accounts,Leads , Contacts... 
    Log.d(TAG, "fetchFriendUpdates");
    //   params.add(new BasicNameValuePair(PARAM_QUERY, "select firstname,lastname,mobile,email,homephone,phone from Contacts;"));
    //        if (lastUpdated != null) {
    //            final SimpleDateFormat formatter =
    //                new SimpleDateFormat("yyyy/MM/dd HH:mm");
    //            formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    //            params.add(new BasicNameValuePair(PARAM_UPDATED, formatter
    //                .format(lastUpdated)));
    //        }

    // HTTP GET REQUEST
    URL url = new URL(auth_url + "/webservice.php?" + URLEncodedUtils.format(params, "utf-8"));
    HttpURLConnection con;
    con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    con.setRequestProperty("Content-length", "0");
    con.setRequestProperty("accept", "application/json");

    con.setUseCaches(false);
    con.setAllowUserInteraction(false);
    int timeout = 10000; // si tiemout pas assez important la connection echouait =>IOEXception
    con.setConnectTimeout(timeout);
    con.setReadTimeout(timeout);
    con.connect();
    int status = con.getResponseCode();

    LastFetchOperationStatus = true;
    if (status == HttpURLConnection.HTTP_OK) {
        // Succesfully connected to the samplesyncadapter server and
        // authenticated.
        // Extract friends data in json format.

        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();

        String response = sb.toString();
        Log.i(TAG, "--response--");
        // <Hack> to bypass vtiger 5.4 webservice bug:
        int idx = response.indexOf("{\"success");
        response = response.substring(idx);
        Log.i(TAG, response);
        // </Hack>
        Log.i(TAG, "--response end--");
        JSONObject result = new JSONObject(response);

        String success = result.getString("success");
        Log.i(TAG, "success is" + success);
        if (success == "true") {
            Log.i(TAG, result.getString("result"));
            final JSONObject data = new JSONObject(result.getString("result"));
            final JSONArray friends = new JSONArray(data.getString("updated"));
            // == VTiger updated contacts ==
            for (int i = 0; i < friends.length(); i++) {
                friendList.add(User.valueOf(friends.getJSONObject(i)));
            }
            // == Vtiger contacts deleted ===
            String deleted_contacts = data.getString("deleted");
            Log.d(TAG, deleted_contacts);
            Log.d(TAG, deleted_contacts.substring(deleted_contacts.indexOf("[")));
            List<String> items = Arrays.asList(
                    deleted_contacts.substring(deleted_contacts.indexOf("[") + 1, deleted_contacts.indexOf("]"))
                            .split("\\s*,\\s*"));
            for (int ii = 0; ii < items.size(); ii++) {
                Log.d(TAG, items.get(ii));
                if (items.get(ii).startsWith("\"4x")) // this is a contact
                {
                    //Log.d(TAG,"{\"id\":"+items.get(ii)+",\"d\":true,\"contact_no\":1}");
                    JSONObject item = new JSONObject(
                            "{\"id\":" + items.get(ii) + ",\"d\":true,\"contact_no\":\"CON1\"}");
                    friendList.add(User.valueOf(item));
                }
                if (items.get(ii).startsWith("\"3x")) // this is an account
                {
                    //Log.d(TAG,"{\"id\":"+items.get(ii)+",\"d\":true,\"contact_no\":1}");
                    JSONObject item = new JSONObject(
                            "{\"id\":" + items.get(ii) + ",\"d\":true,\"account_no\":\"ACC1\"}");
                    friendList.add(User.valueOf(item));
                }
                if (items.get(ii).startsWith("\"2x")) // this is a lead
                {
                    //Log.d(TAG,"{\"id\":"+items.get(ii)+",\"d\":true,\"contact_no\":1}");
                    JSONObject item = new JSONObject(
                            "{\"id\":" + items.get(ii) + ",\"d\":true,\"lead_no\":\"LEA1\"}");
                    friendList.add(User.valueOf(item));
                }
            }
        } else {
            LastFetchOperationStatus = false;
            // FIXME: else false...
            // possible error code :
            //{"success":false,"error":{"code":"AUTHENTICATION_REQUIRED","message":"Authencation required"}}
            //               throw new AuthenticationException();
        }
    } else {
        if (status == HttpURLConnection.HTTP_UNAUTHORIZED) {
            LastFetchOperationStatus = false;

            Log.e(TAG, "Authentication exception in fetching remote contacts");
            throw new AuthenticationException();
        } else {
            LastFetchOperationStatus = false;

            Log.e(TAG, "Server error in fetching remote contacts: ");
            throw new IOException();
        }
    }
    return friendList;
}

From source file:de.langerhans.wallet.ExchangeRatesProvider.java

private static double requestDogeBtcConversion(int provider) {
    HttpURLConnection connection = null;
    Reader reader = null;/*from www  .ja va2s  . c o  m*/
    URL providerUrl;
    switch (provider) {
    case 0:
        providerUrl = CRYPTSY_URL;
        break;
    case 1:
        providerUrl = BTER_URL;
        break;
    default:
        providerUrl = CRYPTSY_URL;
        break;
    }

    try {
        connection = (HttpURLConnection) providerUrl.openConnection();
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            final StringBuilder content = new StringBuilder();
            Io.copy(reader, content);

            try {
                final JSONObject json = new JSONObject(content.toString());
                double rate;
                boolean success;
                switch (provider) {
                case 0:
                    success = json.getBoolean("success");
                    if (!success) {
                        return -1;
                    }
                    rate = json.getJSONObject("data").getJSONObject("last_trade").getDouble("price");
                    break;
                case 1:
                    success = json.getString("result").equals("true"); // Eww bad API!
                    if (!success) {
                        return -1;
                    }
                    rate = Double.valueOf(json.getString("last"));
                    break;
                default:
                    return -1;
                }
                return rate;
            } catch (NumberFormatException e) {
                log.debug("Couldn't get the current exchnage rate from provider " + String.valueOf(provider));
                return -1;
            }

        } else {
            log.debug("http status " + responseCode + " when fetching " + providerUrl);
        }
    } catch (final Exception x) {
        log.debug("problem reading exchange rates", x);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return -1;
}

From source file:org.csware.ee.utils.Tools.java

public static byte[] getByteArray(String path, String cookie) {
    try {//  w w  w. j  a  va2 s.  c o  m
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(6000);
        conn.setReadTimeout(6000);
        conn.setRequestMethod("GET");
        //            conn.setRequestProperty("Cookie",cookie);
        conn.setRequestProperty("Connection", cookie);
        conn.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
        conn.setRequestProperty("Cache-Control", "max-age=0");
        conn.setRequestProperty("Content-Type", "text/html;charset=UTF-8");
        conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
        conn.setRequestProperty("Accept",
                "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        //            conn.setRequestProperty("Host", "pbank.95559.com.cn");
        //            conn.setRequestProperty("Origin", "https://creditcardapp.bankcomm.com");
        //            conn.setRequestProperty("Referer", "https://pbank.95559.com.cn/personbank/credit/pb0525_apply_result_qry_req.jsp");
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36");
        if (conn.getResponseCode() == 200) {
            InputStream inputStream = conn.getInputStream();
            return streamToByte(inputStream);
        } else {
            //Log.i("ToolsImg",conn.getResponseCode()+"");
            //Log.i("ToolsImg",conn.getResponseMessage()+"");
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return null;
}

From source file:org.csware.ee.utils.Tools.java

/**
 * ??byte// www.  java2s . c  o  m
 * @param path 
 * @return  byte[]
 * @throws Exception
 */
public static byte[] getByteArray(String path) {
    try {
        String boundary = "*****";
        //            System.setProperty("http.keepAlive", "false");
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(6000);
        conn.setReadTimeout(6000);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("connection", "Keep-Alive");
        //            conn.setRequestProperty("Content-Type",
        //                    "multipart/form-data;boundary=" + boundary);
        conn.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
        //            conn.setRequestProperty("Cache-Control", "max-age=0");
        conn.setRequestProperty("Content-Type", "text/html;charset=UTF-8");
        //            conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
        //            conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        //            conn.setRequestProperty("Host", "pbank.95559.com.cn");
        //            conn.setRequestProperty("Origin", "https://creditcardapp.bankcomm.com");
        //            conn.setRequestProperty("Referer", "https://pbank.95559.com.cn/personbank/credit/pb0525_apply_result_qry_req.jsp");
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36");

        if (conn.getResponseCode() == 200) {
            InputStream inputStream = conn.getInputStream();
            return streamToByte(inputStream);
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return null;
}

From source file:com.example.android.networkconnect.DownloadUrl.java

public InputStream downloadUrl(String urlString) throws IOException {
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000 /* milliseconds */);
    conn.setConnectTimeout(15000 /* milliseconds */);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);//from ww  w .j  a  v  a2 s . c  om
    conn.connect();
    InputStream stream = conn.getInputStream();
    return stream;
}

From source file:com.none.tom.simplerssreader.net.FeedDownloader.java

@SuppressWarnings("ConstantConditions")
public static InputStream getInputStream(final Context context, final String feedUrl) {
    final ConnectivityManager manager = context.getSystemService(ConnectivityManager.class);
    final NetworkInfo info = manager.getActiveNetworkInfo();

    if (info == null || !info.isConnected()) {
        ErrorHandler.setErrno(ErrorHandler.ERROR_NETWORK);
        LogUtils.logError("No network connection");
        return null;
    }//from   w w w .j  av a  2 s.  c o m

    URL url;
    try {
        url = new URL(feedUrl);
    } catch (final MalformedURLException e) {
        ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_BAD_REQUEST, e);
        return null;
    }

    final boolean[] networkPrefs = DefaultSharedPrefUtils.getNetworkPreferences(context);
    final boolean useHttpTorProxy = networkPrefs[0];
    final boolean httpsOnly = networkPrefs[1];
    final boolean followRedir = networkPrefs[2];

    for (int nrRedirects = 0;; nrRedirects++) {
        if (nrRedirects >= HTTP_NR_REDIRECTS_MAX) {
            ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_TOO_MANY_REDIRECTS);
            LogUtils.logError("Too many redirects");
            return null;
        }

        HttpURLConnection conn = null;

        try {
            if (httpsOnly && url.getProtocol().equalsIgnoreCase("http")) {
                ErrorHandler.setErrno(ErrorHandler.ERROR_HTTPS_ONLY);
                LogUtils.logError("Attempting insecure connection");
                return null;
            }

            if (useHttpTorProxy) {
                conn = (HttpURLConnection) url.openConnection(new Proxy(Proxy.Type.HTTP,
                        new InetSocketAddress(InetAddress.getByName(HTTP_PROXY_TOR_IP), HTTP_PROXY_TOR_PORT)));
            } else {
                conn = (HttpURLConnection) url.openConnection();
            }

            conn.setRequestProperty("Accept-Charset", StandardCharsets.UTF_8.name());

            conn.setConnectTimeout(HTTP_URL_DEFAULT_TIMEOUT);
            conn.setReadTimeout(HTTP_URL_DEFAULT_TIMEOUT);

            conn.connect();

            final int responseCode = conn.getResponseCode();

            switch (responseCode) {
            case HttpURLConnection.HTTP_OK:
                return getInputStream(conn.getInputStream());
            case HttpURLConnection.HTTP_MOVED_PERM:
            case HttpURLConnection.HTTP_MOVED_TEMP:
            case HttpURLConnection.HTTP_SEE_OTHER:
            case HTTP_TEMP_REDIRECT:
                if (followRedir) {
                    final String location = conn.getHeaderField("Location");
                    url = new URL(url, location);

                    if (responseCode == HttpURLConnection.HTTP_MOVED_PERM) {
                        SharedPrefUtils.updateSubscriptionUrl(context, url.toString());
                    }
                    continue;
                }
                ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_FOLLOW_REDIRECT_DENIED);
                LogUtils.logError("Couldn't follow redirect");
                return null;
            default:
                if (responseCode < 0) {
                    ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_RESPONSE);
                    LogUtils.logError("No valid HTTP response");
                    return null;
                } else if (responseCode >= 400 && responseCode <= 500) {
                    ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_CLIENT);
                } else if (responseCode >= 500 && responseCode <= 600) {
                    ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_SERVER);
                } else {
                    ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_UNHANDLED);
                }
                LogUtils.logError("Error " + responseCode + ": " + conn.getResponseMessage());
                return null;
            }
        } catch (final IOException e) {
            if ((e instanceof ConnectException && e.getMessage().equals("Network is unreachable"))
                    || e instanceof SocketTimeoutException || e instanceof UnknownHostException) {
                ErrorHandler.setErrno(ErrorHandler.ERROR_NETWORK, e);
            } else {
                ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_UNHANDLED, e);
            }
            return null;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }
}

From source file:de.onelogic.android.weatherdemo.WeatherFetchTask.java

private String downloadUrl(String urlString) throws IOException {
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000 /* milliseconds */);
    conn.setConnectTimeout(15000 /* milliseconds */);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);//w ww.  j  a va  2  s .  co  m
    // Starts the query
    conn.connect();
    InputStream is = conn.getInputStream();

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));

    String line = null;
    StringBuilder sb = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }
    return sb.toString();
}

From source file:piuk.MyRemoteWallet.java

private static String fetchURL(String URL) throws Exception {

    if (URL.indexOf("?") > 0) {
        URL += "&api_code=" + getApiCode();
    } else {//  ww  w .  j  a v  a 2  s  .  co  m
        URL += "?api_code=" + getApiCode();
    }

    URL url = new URL(URL);

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    try {
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestMethod("GET");

        connection.setConnectTimeout(180000);
        connection.setReadTimeout(180000);

        connection.setInstanceFollowRedirects(false);

        connection.connect();

        if (connection.getResponseCode() == 200)
            return IOUtils.toString(connection.getInputStream(), "UTF-8");
        else if (connection.getResponseCode() == 500)
            throw new Exception("Error From Server: " + IOUtils.toString(connection.getErrorStream(), "UTF-8"));
        else
            throw new Exception("Unknown response from server (" + connection.getResponseCode() + ") "
                    + IOUtils.toString(connection.getErrorStream(), "UTF-8"));

    } finally {
        connection.disconnect();
    }
}

From source file:com.adguard.commons.web.UrlUtils.java

/**
 * Downloads content from the specified url using specified proxy (or do not using it) and timeouts.
 * Returns null if there's an error./*from  w  ww .  j a  va2 s  .  co  m*/
 *
 * @param url           url
 * @param proxy         proxy to use
 * @param readTimeout   read timeout
 * @param socketTimeout connection timeout
 * @return Downloaded string
 */
public static String downloadString(URL url, Proxy proxy, int readTimeout, int socketTimeout, String encoding,
        int triesCount) {
    IOException lastException = null;

    for (int i = 0; i < triesCount; i++) {
        lastException = null;
        HttpURLConnection connection = null;
        InputStream inputStream = null;

        try {
            connection = (HttpURLConnection) (proxy == null ? url.openConnection() : url.openConnection(proxy));
            connection.setReadTimeout(readTimeout);
            connection.setConnectTimeout(socketTimeout);
            connection.connect();
            inputStream = connection.getInputStream();
            return IOUtils.toString(inputStream, encoding);
        } catch (IOException ex) {
            if (LOG.isDebugEnabled()) {
                LOG.warn("Error downloading string from {}. Try number: {}. Cause:\r\n", url, triesCount, ex);
            } else {
                LOG.warn("Error downloading string from {}. Try number: {}. Cause:{}", url, triesCount,
                        ex.getMessage());
            }
            lastException = ex;
        } finally {
            IOUtils.closeQuietly(inputStream);
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    if (lastException != null) {
        LOG.error("Could not download string from url: " + url, lastException);
    }

    return null;
}

From source file:com.orchestra.portale.external.services.manager.BikeSharingService.java

@Override
public String getResponse(Map<String, String[]> mapParams) {
    try {/*from   w  w  w .jav  a  2 s  .  co m*/

        HttpURLConnection urlConnection = (HttpURLConnection) new URL(baseUrl).openConnection();
        urlConnection.setConnectTimeout(15000);
        urlConnection.setReadTimeout(30000);

        urlConnection.addRequestProperty("Accept-Language", Locale.getDefault().toString().replace('_', '-'));

        String result = IOUtils.toString(urlConnection.getInputStream());
        urlConnection.disconnect();

        return result;

    } catch (IOException e) {
        return "response{code:1,error:" + e.getMessage() + "}";
    }
}