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:foam.starwisp.NetworkManager.java

private void Post(String u, String type, String data, String CallbackName) {
    try {//from  w ww  .  j  a v  a  2s . co m
        Log.i("starwisp", "posting: " + u);
        URL url = new URL(u);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        con.setUseCaches(false);
        con.setReadTimeout(100000 /* milliseconds */);
        con.setConnectTimeout(150000 /* milliseconds */);
        con.setRequestMethod("POST");
        con.setDoInput(true);
        con.setDoOutput(true);

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("data", data));

        OutputStream os = con.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(getQuery(params));
        writer.flush();
        writer.close();
        os.close();

        // 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.spotify.helios.client.DefaultHttpConnector.java

private HttpURLConnection connect0(final URI ipUri, final String method, final byte[] entity,
        final Map<String, List<String>> headers, final String endpointHost) throws IOException {
    if (log.isTraceEnabled()) {
        log.trace("req: {} {} {} {} {} {}", method, ipUri, headers.size(),
                Joiner.on(',').withKeyValueSeparator("=").join(headers), entity.length,
                Json.asPrettyStringUnchecked(entity));
    } else {//  ww w . ja  va2s.  c om
        log.debug("req: {} {} {} {}", method, ipUri, headers.size(), entity.length);
    }

    final HttpURLConnection connection = (HttpURLConnection) ipUri.toURL().openConnection();
    handleHttps(connection, endpointHost, hostnameVerifierProvider, extraHttpsHandler);

    connection.setRequestProperty("Accept-Encoding", "gzip");
    connection.setInstanceFollowRedirects(false);
    connection.setConnectTimeout(httpTimeoutMillis);
    connection.setReadTimeout(httpTimeoutMillis);
    for (Map.Entry<String, List<String>> header : headers.entrySet()) {
        for (final String value : header.getValue()) {
            connection.addRequestProperty(header.getKey(), value);
        }
    }
    if (entity.length > 0) {
        connection.setDoOutput(true);
        connection.getOutputStream().write(entity);
    }

    setRequestMethod(connection, method, connection instanceof HttpsURLConnection);

    return connection;
}

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

/**
 * @param urlStr      String email built in query with URLEncoded email
 * @param showAvailable  If true, return the string "Data Available" for
 *                     fields the account is not subscribed to but for which Rapleaf has data
 * @return            Returns a JSONObject hash from fields onto field values
 * @throws Exception  Throws error code on all HTTP statuses outside of 200 <= status < 300
 *//*from ww  w  .j av  a2 s  . c  o  m*/
protected JSONObject getJsonResponse(String urlStr, boolean showAvailable) throws Exception {
    if (showAvailable) {
        urlStr = urlStr + "&show_available=true";
    }
    URL url = new URL(urlStr);
    HttpURLConnection handle = (HttpURLConnection) url.openConnection();
    handle.setRequestProperty("User-Agent", getUserAgent());
    handle.setConnectTimeout(timeout);
    handle.setReadTimeout(timeout);
    BufferedReader in = new BufferedReader(new InputStreamReader(handle.getInputStream()));
    String responseBody = in.readLine();
    in.close();
    int responseCode = handle.getResponseCode();
    if (responseCode < 200 || responseCode > 299) {
        throw new Exception("Error Code " + responseCode + ": " + responseBody);
    }
    if (responseBody == null || responseBody.equals("")) {
        responseBody = "{}";
    }
    return new JSONObject(responseBody);
}

From source file:com.alexkli.jhb.Worker.java

@Override
public void run() {
    try {//from  w  w  w .j  a  va 2  s. c om
        while (true) {
            long start = System.nanoTime();

            QueueItem<HttpRequestBase> item = queue.take();

            idleAvg.add(System.nanoTime() - start);

            if (item.isPoisonPill()) {
                return;
            }

            HttpRequestBase request = item.getRequest();

            if ("java".equals(config.client)) {
                System.setProperty("http.keepAlive", "false");

                item.sent();

                try {
                    HttpURLConnection http = (HttpURLConnection) new URL(request.getURI().toString())
                            .openConnection();
                    http.setConnectTimeout(5000);
                    http.setReadTimeout(5000);
                    int statusCode = http.getResponseCode();

                    consumeAndCloseStream(http.getInputStream());

                    if (statusCode == 200) {
                        item.done();
                    } else {
                        item.failed();
                    }
                } catch (IOException e) {
                    System.err.println("Failed request: " + e.getMessage());
                    e.printStackTrace();
                    //                        System.exit(2);
                    item.failed();
                }
            } else if ("ahc".equals(config.client)) {
                try {
                    item.sent();

                    try (CloseableHttpResponse response = httpClient.execute(request, context)) {
                        int statusCode = response.getStatusLine().getStatusCode();
                        if (statusCode == 200) {
                            item.done();
                        } else {
                            item.failed();
                        }
                    }
                } catch (IOException e) {
                    System.err.println("Failed request: " + e.getMessage());
                    item.failed();
                }
            } else if ("fast".equals(config.client)) {
                try {
                    URI uri = request.getURI();

                    item.sent();

                    InetAddress addr = InetAddress.getByName(uri.getHost());
                    Socket socket = new Socket(addr, uri.getPort());
                    PrintWriter out = new PrintWriter(socket.getOutputStream());
                    //                        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    // send an HTTP request to the web server
                    out.println("GET / HTTP/1.1");
                    out.append("Host: ").append(uri.getHost()).append(":").println(uri.getPort());
                    out.println("Connection: Close");
                    out.println();
                    out.flush();

                    // read the response
                    consumeAndCloseStream(socket.getInputStream());
                    //                        boolean loop = true;
                    //                        StringBuilder sb = new StringBuilder(8096);
                    //                        while (loop) {
                    //                            if (in.ready()) {
                    //                                int i = 0;
                    //                                while (i != -1) {
                    //                                    i = in.read();
                    //                                    sb.append((char) i);
                    //                                }
                    //                                loop = false;
                    //                            }
                    //                        }
                    item.done();
                    socket.close();

                } catch (IOException e) {
                    e.printStackTrace();
                    item.failed();
                }
            } else if ("nio".equals(config.client)) {
                URI uri = request.getURI();

                item.sent();

                String requestBody = "GET / HTTP/1.1\n" + "Host: " + uri.getHost() + ":" + uri.getPort() + "\n"
                        + "Connection: Close\n\n";

                try {
                    InetSocketAddress addr = new InetSocketAddress(uri.getHost(), uri.getPort());
                    SocketChannel channel = SocketChannel.open();
                    channel.socket().setSoTimeout(5000);
                    channel.connect(addr);

                    ByteBuffer msg = ByteBuffer.wrap(requestBody.getBytes());
                    channel.write(msg);
                    msg.clear();

                    ByteBuffer buf = ByteBuffer.allocate(1024);

                    int count;
                    while ((count = channel.read(buf)) != -1) {
                        buf.flip();

                        byte[] bytes = new byte[count];
                        buf.get(bytes);

                        buf.clear();
                    }
                    channel.close();

                    item.done();

                } catch (IOException e) {
                    e.printStackTrace();
                    item.failed();
                }
            }
        }
    } catch (InterruptedException e) {
        System.err.println("Worker thread [" + this.toString() + "] was interrupted: " + e.getMessage());
    }
}

From source file:com.koodroid.chicken.KooDroidHelper.java

public void checkForUpdateOnBackgroundThread(final MainActivity activity) {
    if (mAlreadyCheckedForUpdates) {
        return;//w  w  w.j av  a 2s  .c  o m
    }
    mAlreadyCheckedForUpdates = true;
    new AsyncTask<Void, Void, Void>() {

        @Override
        protected Void doInBackground(Void... params) {
            SharedPreferences prefs = activity.getSharedPreferences(KooDroidHelper.class.getName(),
                    Context.MODE_PRIVATE);
            Random random = new Random();
            long interval = random.nextInt(7) + 3; // [3, 10)
            long timestamp = prefs.getLong("LastCheckTimestamp", 0);
            long now = System.currentTimeMillis();
            if ((now - timestamp < interval * 24 * 60 * 60 * 1000) && !DEBUG) {
                return null;
            }
            prefs.edit().putLong("LastCheckTimestamp", now).commit();
            HttpURLConnection urlConnection = null;
            BufferedReader in = null;
            try {

                URL url = new URL(mUpdateUrl);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setConnectTimeout(60000);
                urlConnection.setReadTimeout(60000);
                urlConnection.setUseCaches(false);
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();
                if (urlConnection.getResponseCode() == 200) {
                    InputStreamReader reader = new InputStreamReader(urlConnection.getInputStream());
                    in = new BufferedReader(reader);
                    StringBuilder response = new StringBuilder();
                    for (String line = in.readLine(); line != null; line = in.readLine()) {
                        response.append(line);
                    }

                    try {
                        JSONObject jsonObj = new JSONObject(response.toString());
                        mLatestVersion = jsonObj.getString("version_code");
                        mDownloadUrl = jsonObj.getString("download_url");
                    } catch (JSONException e) {
                        System.out.println("Json parse error");
                        e.printStackTrace();
                    }
                    //                        
                    //                        JSONTokener jsonParser = new JSONTokener(response.toString());    
                    //                        // ?json?JSONObject    
                    //                        // ??"name" : nextValue"yuanzhifei89"String    
                    //                        JSONObject person = (JSONObject) jsonParser.nextValue();    
                    //                        // ?JSON?    
                    //                        person.getJSONArray("phone");    
                    //                        person.getString("name");    
                    //                        person.getInt("age");    
                    //                        person.getJSONObject("address");    
                    //                        person.getBoolean("married");    
                    //                        
                    //mLatestVersion = response.toString();
                    int versionCode = Integer.valueOf(mLatestVersion);
                    mUpdateAvailable = Integer.valueOf(mLatestVersion) > Integer
                            .valueOf(getPackageVersionCode(activity));
                }
            } catch (Exception e) {
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                    }
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            //maybeShowUpdateDialog(activity);
        }
    }.execute();
}

From source file:de.ingrid.iplug.csw.dsc.cswclient.impl.XMLPostRequest.java

/**
 * Send the given request to the server.
 * @param serverURL/*from w w  w  .j  a v a2 s.c om*/
 * @param payload
 * @return Document
 * @throws Exception 
 */
protected Document sendRequest(String requestURL, OMElement payload) throws Exception {
    // and make the call
    Document result = null;
    HttpURLConnection conn = null;
    try {
        URL url = new URL(requestURL);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setAllowUserInteraction(false);
        conn.setReadTimeout(10000);
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-type", "text/xml");
        conn.connect();

        // send the request
        String xmlToSend = serializeElement(payload.cloneOMElement());
        if (log.isDebugEnabled())
            log.debug("Request: " + xmlToSend);
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(xmlToSend);
        wr.flush();
        wr.close();

        // Get response data.
        int code = conn.getResponseCode();
        if (code >= 200 && code < 300) {
            DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            domFactory.setNamespaceAware(true);
            DocumentBuilder builder = domFactory.newDocumentBuilder();
            result = builder.parse(conn.getInputStream());
        }
        conn.disconnect();
        conn = null;
    } catch (Exception e) {
        throw e;
    } finally {
        if (conn != null)
            conn.disconnect();
    }
    return result;
}

From source file:edu.hackathon.perseus.core.httpSpeedTest.java

public double testDownload() {
    double bw = 0.0;

    try {//w  w w .  j  a v a2  s .  c  o m
        Date oldTime = new Date();
        URL obj = new URL(amazonDomain + "/download_test.bin");
        HttpURLConnection httpGetCon = (HttpURLConnection) obj.openConnection();
        // optional default is GET
        httpGetCon.setRequestMethod("GET");
        httpGetCon.setConnectTimeout(5000); //set timeout to 5 seconds
        httpGetCon.setReadTimeout(5000);
        //add request header
        httpGetCon.setRequestProperty("User-Agent", USER_AGENT);
        if (httpGetCon.getResponseCode() == 200) {
            Date newTime = new Date();
            double milliseconds = newTime.getTime() - oldTime.getTime();
            int lenght = httpGetCon.getContentLength();

            bw = ((double) lenght * 8) / (milliseconds * (double) 1000);
        }

        //         BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        //         String inputLine;
        //         StringBuffer response = new StringBuffer();
        //         while ((inputLine = in.readLine()) != null) {
        //            response.append(inputLine);
        //         }
        //         in.close();
        //
        //         //print result
        //         System.out.println(response.toString());
    } catch (MalformedURLException e) {
        System.out.println("MalformedURLException is fired!");
    } catch (IOException e) {
        System.out.println("Exception is fired in download test. error:" + e.getMessage());
    }

    return bw;
}

From source file:cn.com.zzwfang.http.HttpExecuter.java

@Override
public byte[] img(String urlString) {
    HttpURLConnection httpURLConnection = null;
    InputStream inputStream = null;
    ByteArrayOutputStream outputStream = null;
    try {/*from   w  ww . j  av  a 2s . com*/
        URL url = new URL(urlString);
        httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.setReadTimeout(10 * 1000);
        if (httpURLConnection.getResponseCode() == 200) {
            inputStream = httpURLConnection.getInputStream();
            outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = -1;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.close();
            inputStream.close();
            return outputStream.toByteArray();
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }
        try {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:iZiggiClient.java

private JSONObject doAction(String cmd, String val) {
    String actUrl = requestUrl + api + "?id=" + userId + "&pwd=" + userPass + "&command=" + cmd;
    if (!val.equals(""))
        actUrl += "&value=" + val;
    URL url = null;//from  w w w.  j a  v a2  s.c  o m
    BufferedReader reader = null;
    StringBuilder stringBuilder;
    JSONObject json = null;
    String extraMessage = "";
    try {
        // create the HttpURLConnection
        url = new URL(actUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // just want to do an HTTP GET here
        connection.setRequestMethod("GET");

        // give it 15 seconds to respond
        connection.setReadTimeout(15 * 1000);
        connection.connect();

        // read the output from the server
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        stringBuilder = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }

        json = new JSONObject(stringBuilder.toString());
    } catch (UnknownHostException e) {
        try {
            json = new JSONObject("{Status:5}");
            extraMessage = " - host name error";
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
    } catch (ConnectException e) {
        try {
            json = new JSONObject("{Status:5}");
            extraMessage = " - connect error";
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
    } catch (NullPointerException e) {
        try {
            json = new JSONObject("{Status:5}");
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
    try {
        json.put("Message", getMessage(json.getInt("Status")) + extraMessage);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return json;
}

From source file:com.google.samples.quickstart.signin.MainActivity.java

private String downloadUrl(String myurl, String tokenid) throws IOException {
    InputStream is = null;/*from   w  w w. j ava2s.co m*/
    // Only display the first 500 characters of the retrieved
    // web page content.
    int len = 500;

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "application/json");

        JSONObject cred = new JSONObject();
        cred.put("tokenid", tokenid);

        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(cred.toString());
        wr.flush();
        //con.setRequestMethod("POST");
        //conn.setRequestProperty("tokenid",tokenid);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        Log.d(TAG, "The response is: " + response);

        is = conn.getInputStream();

        // Convert the InputStream into a string
        String contentAsString = readIt(is, len);
        return contentAsString;

        // Makes sure that the InputStream is closed after the app is
        // finished using it.
    } catch (JSONException e) {
        e.printStackTrace();
        return null;
    } finally {
        if (is != null) {
            is.close();
        }
    }
}