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:edu.usf.cutr.opentripplanner.android.pois.Nominatim.java

public JSONArray requestPlaces(String paramName, String left, String top, String right, String bottom) {
    StringBuilder builder = new StringBuilder();

    String encodedParamName;//from   w w w . ja  v  a2 s.c o  m
    String encodedParamLeft = "";
    String encodedParamTop = "";
    String encodedParamRight = "";
    String encodedParamBottom = "";
    try {
        encodedParamName = URLEncoder.encode(paramName, OTPApp.URL_ENCODING);
        if ((left != null) && (top != null) && (right != null) && (bottom != null)) {
            encodedParamLeft = URLEncoder.encode(left, OTPApp.URL_ENCODING);
            encodedParamTop = URLEncoder.encode(top, OTPApp.URL_ENCODING);
            encodedParamRight = URLEncoder.encode(right, OTPApp.URL_ENCODING);
            encodedParamBottom = URLEncoder.encode(bottom, OTPApp.URL_ENCODING);
        }
    } catch (UnsupportedEncodingException e1) {
        Log.e(OTPApp.TAG, "Error encoding Nominatim request");
        e1.printStackTrace();
        return null;
    }

    request += "&q=" + encodedParamName;
    if ((left != null) && (top != null) && (right != null) && (bottom != null)) {
        request += "&viewbox=" + encodedParamLeft + "," + encodedParamTop + "," + encodedParamRight + ","
                + encodedParamBottom;
        request += "&bounded=1";
    }

    request += "&key=" + mApiKey;

    Log.d(OTPApp.TAG, request);

    HttpURLConnection urlConnection = null;

    try {
        URL url = new URL(request);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(OTPApp.HTTP_CONNECTION_TIMEOUT);
        urlConnection.setReadTimeout(OTPApp.HTTP_SOCKET_TIMEOUT);
        urlConnection.connect();
        int status = urlConnection.getResponseCode();

        if (status == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } else {
            Log.e(OTPApp.TAG, "Error obtaining Nominatim response, status code: " + status);
        }
    } catch (IOException e) {
        e.printStackTrace();
        Log.e(OTPApp.TAG, "Error obtaining Nominatim response" + e.toString());
        return null;
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    Log.d(OTPApp.TAG, builder.toString());

    JSONArray json = null;
    try {
        json = new JSONArray(builder.toString());
    } catch (JSONException e) {
        Log.e(OTPApp.TAG, "Error parsing Nominatim data " + e.toString());
    }

    return json;
}

From source file:it.publisys.liferay.hook.shibboleth.ShibbolethPostLogoutAction.java

/**
 * Effettua una {@link HttpURLConnection} inviando anche i cookies
 *
 * @param url     url/*from w  ww  . ja va2  s  .  co  m*/
 * @param cookies cookies
 * @return response code
 */
private int _connect(String url, String cookies) {
    int responseCode = -1;
    try {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public void checkClientTrusted(java.security.cert.X509Certificate[] xcs, String string)
                    throws CertificateException {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] xcs, String string)
                    throws CertificateException {
            }

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };

        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
    }

    HttpURLConnection connection = null;
    try {
        URL _url = new URL(url);
        connection = (HttpURLConnection) _url.openConnection(Proxy.NO_PROXY);
        connection.setRequestProperty("Cookie", cookies);
        connection.setReadTimeout(5000);
        connection.setRequestMethod("GET");

        responseCode = connection.getResponseCode();
        _log.info("Logout Shibb response code: " + responseCode);

        if (responseCode == 200 && _log.isDebugEnabled()) {
            BufferedReader br = null;
            try {
                br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                StringBuilder _buffer = new StringBuilder();
                String line = null;
                while ((line = br.readLine()) != null) {
                    _buffer.append(line);
                }
                _log.debug(_buffer.toString());
            } finally {
                if (br != null) {
                    br.close();
                }
            }

        }

    } catch (MalformedURLException mue) {
        mue.printStackTrace(System.err);
    } catch (IOException ioe) {
        ioe.printStackTrace(System.err);
    } finally {
        try {
            if (connection != null) {
                connection.disconnect();
            }
        } catch (Exception ex) {
            ex.printStackTrace(System.out);
        }
    }
    return responseCode;
}

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

/**
 * Sends a POST request/*from w ww .j a v a 2  s  .c  om*/
 *
 * @param url           URL
 * @param postData      Post request body
 * @param encoding      Post request body encoding
 * @param contentType   Body content type
 * @param compress      If true - compress bod
 * @param readTimeout   Read timeout
 * @param socketTimeout Socket timeout
 * @return Response
 */
public static String postRequest(URL url, String postData, String encoding, String contentType,
        boolean compress, int readTimeout, int socketTimeout) {
    HttpURLConnection connection = null;
    OutputStream outputStream = null;

    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        if (contentType != null) {
            connection.setRequestProperty("Content-Type", contentType);
        }
        if (compress) {
            connection.setRequestProperty("Content-Encoding", "gzip");
        }
        connection.setConnectTimeout(socketTimeout);
        connection.setReadTimeout(readTimeout);
        connection.setDoOutput(true);
        connection.connect();
        if (postData != null) {
            outputStream = connection.getOutputStream();

            if (compress) {
                outputStream = new GZIPOutputStream(outputStream);
            }

            if (encoding != null) {
                IOUtils.write(postData, outputStream, encoding);
            } else {
                IOUtils.write(postData, outputStream);
            }

            if (compress) {
                ((GZIPOutputStream) outputStream).finish();
            } else {
                outputStream.flush();
            }
        }

        return IOUtils.toString(connection.getInputStream(), encoding);
    } catch (Exception ex) {
        LOG.error("Error posting request to {}, post data length={}\r\n", url, StringUtils.length(postData),
                ex);
        // Ignoring exception
        return null;
    } finally {
        IOUtils.closeQuietly(outputStream);

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

From source file:foam.blob.RestBlobService.java

@Override
public Blob put_(X x, Blob blob) {
    if (blob instanceof IdentifiedBlob) {
        return blob;
    }/*from ww  w  . j  a va 2s.c  o m*/

    HttpURLConnection connection = null;
    OutputStream os = null;
    InputStream is = null;

    try {
        URL url = new URL(address_);
        connection = (HttpURLConnection) url.openConnection();

        //configure HttpURLConnection
        connection.setConnectTimeout(5 * 1000);
        connection.setReadTimeout(5 * 1000);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        //set request method
        connection.setRequestMethod("PUT");

        //configure http header
        connection.setRequestProperty("Accept", "*/*");
        connection.setRequestProperty("Connection", "keep-alive");
        connection.setRequestProperty("Content-Type", "application/octet-stream");

        // get connection ouput stream
        os = connection.getOutputStream();

        //output blob into connection
        blob.read(os, 0, blob.getSize());

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new RuntimeException("Upload failed");
        }

        is = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        CharBuffer cb = CharBuffer.allocate(65535);
        reader.read(cb);
        cb.rewind();

        return (Blob) getX().create(JSONParser.class).parseString(cb.toString(), IdentifiedBlob.class);
    } catch (Throwable t) {
        t.printStackTrace();
        throw new RuntimeException(t);
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
        IOUtils.close(connection);
    }
}

From source file:com.galileha.smarthome.SmartHome.java

/**
 * Read home.json from Server//from   w w  w  .j a  v a2  s  . c o  m
 * 
 * @param URL
 * @return
 * @throws IOException
 *             , MalformedURLException, JSONException
 */
public void getHomeStatus() throws IOException, MalformedURLException, JSONException {
    // Set URL
    // Connect to Intel Galileo get Device Status
    HttpURLConnection httpCon = (HttpURLConnection) homeJSONUrl.openConnection();
    httpCon.setReadTimeout(10000);
    httpCon.setConnectTimeout(15000);
    httpCon.setRequestMethod("GET");
    httpCon.setDoInput(true);
    httpCon.connect();
    // Read JSON File as InputStream
    InputStream readStream = httpCon.getInputStream();
    Scanner scan = new Scanner(readStream).useDelimiter("\\A");
    // Set stream to String
    String jsonFile = scan.hasNext() ? scan.next() : "";
    // Initialize serveFile as read string
    homeInfo = new JSONObject(jsonFile);
    httpCon.disconnect();
}

From source file:com.vimc.ahttp.HurlWorker.java

/**
 * Opens an {@link HttpURLConnection} with parameters.
 * //from   w w w .j  a va  2s.  c o m
 * @param url
 * @return an open connection
 * @throws IOException
 */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);

    connection.setConnectTimeout(request.connectTimeout);
    connection.setReadTimeout(request.soTimeout);
    connection.setUseCaches(false);
    connection.setDoInput(true);
    // connection.setRequestProperty("Connection", "close");

    if ("https".equals(url.getProtocol())) {
        if (mSslSocketFactory != null) {
            ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
        } else {
            setDefaultSSLSocketFactory();
        }
    }

    return connection;
}

From source file:com.mywork.framework.util.RemoteHttpUtil.java

/**
 *  JDK???//from   w  ww .  ja v  a 2  s . co  m
 */

private void fetchContentByJDKConnection(HttpServletResponse response, String contentUrl) throws IOException {

    HttpURLConnection connection = (HttpURLConnection) new URL(contentUrl).openConnection();
    // Socket
    connection.setReadTimeout(TIMEOUT_SECONDS * 1000);
    try {
        connection.connect();

        // ?
        InputStream input;
        try {
            input = connection.getInputStream();
        } catch (FileNotFoundException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, contentUrl + " is not found.");
            return;
        }

        // Header
        response.setContentType(connection.getContentType());
        if (connection.getContentLength() > 0) {
            response.setContentLength(connection.getContentLength());
        }

        // 
        OutputStream output = response.getOutputStream();
        try {
            // byte?InputStreamOutputStream, ?4k.
            IOUtils.copy(input, output);
            output.flush();
        } finally {
            // ??InputStream.
            IOUtils.closeQuietly(input);
        }
    } finally {
        connection.disconnect();
    }
}

From source file:edu.usf.cutr.opentripplanner.android.pois.GooglePlaces.java

public JSONObject requestPlaces(String paramLocation, String paramRadius, String paramName) {
    StringBuilder builder = new StringBuilder();

    String encodedParamLocation = "";
    String encodedParamRadius = "";
    String encodedParamName;/*from w w w .  ja va  2 s. c o  m*/
    try {
        if ((paramLocation != null) && (paramRadius != null)) {
            encodedParamLocation = URLEncoder.encode(paramLocation, OTPApp.URL_ENCODING);
            encodedParamRadius = URLEncoder.encode(paramRadius, OTPApp.URL_ENCODING);
        }
        encodedParamName = URLEncoder.encode(paramName, OTPApp.URL_ENCODING);
    } catch (UnsupportedEncodingException e1) {
        Log.e(OTPApp.TAG, "Error encoding Google Places request");
        e1.printStackTrace();
        return null;
    }

    if ((paramLocation != null) && (paramRadius != null)) {
        request += "location=" + encodedParamLocation;
        request += "&radius=" + encodedParamRadius;
        request += "&query=" + encodedParamName;
    } else {
        request += "query=" + encodedParamName;
    }
    request += "&sensor=false";
    request += "&key=" + getApiKey();

    Log.d(OTPApp.TAG, request);

    HttpURLConnection urlConnection = null;

    try {
        URL url = new URL(request);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(OTPApp.HTTP_CONNECTION_TIMEOUT);
        urlConnection.setReadTimeout(OTPApp.HTTP_SOCKET_TIMEOUT);
        urlConnection.connect();
        int status = urlConnection.getResponseCode();

        if (status == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } else {
            Log.e(OTPApp.TAG, "Error obtaining Google Places response, status code: \" + status");
        }
    } catch (IOException e) {
        Log.e(OTPApp.TAG, "Error obtaining Google Places response" + e.toString());
        e.printStackTrace();
        return null;
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    Log.d(OTPApp.TAG, builder.toString());

    JSONObject json = null;
    try {
        json = new JSONObject(builder.toString());
    } catch (JSONException e) {
        Log.e(OTPApp.TAG, "Error parsing Google Places data " + e.toString());
    }

    return json;
}

From source file:com.threeti.proxy.RequestFilter.java

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    String path = request.getServletPath();
    String pathInfo = path.substring(path.lastIndexOf("/"));

    if (pathInfo == null) {
        response.getWriter().write("error");
    } else {/*from   www  .java  2s.com*/
        if (path.contains("/proxy")) {
            pathInfo = path.substring(path.lastIndexOf("/proxy") + 6);
            if ("POST".equals(request.getMethod())) { // POST
                String urlString = this.baseURL + pathInfo;
                logger.info(urlString);
                String s = this.getParams(req).substring(0, this.getParams(req).length() - 1);
                byte[] data = s.getBytes("utf-8");
                HttpURLConnection conn = null;
                DataOutputStream outStream = null;
                URL httpUrl = new URL(urlString);
                conn = (HttpURLConnection) httpUrl.openConnection();
                conn.setConnectTimeout(7000);
                conn.setReadTimeout(7000);
                conn.setUseCaches(false);
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("Charset", "utf-8");
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.setRequestProperty("Content-Length", String.valueOf(data.length));
                outStream = new DataOutputStream(conn.getOutputStream());
                outStream.write(data);
                outStream.flush();
                if (conn.getResponseCode() == 200) {
                    InputStream in = conn.getInputStream();
                    IOUtils.copy(in, response.getOutputStream());
                } else {
                    try {
                        throw new Exception("ResponseCode=" + conn.getResponseCode());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            } else if ("DELETE".equals(request.getMethod())) {
                String urlString = this.baseURL + pathInfo + "?" + this.getParams(req);
                logger.info(urlString);
                HttpURLConnection conn = null;
                URL url = new URL(urlString);
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(7000);
                conn.setReadTimeout(7000);
                conn.setUseCaches(false);
                conn.setDoOutput(true);
                conn.setRequestMethod("DELETE");
                if (conn.getResponseCode() == 200) {
                    InputStream in = conn.getInputStream();
                    IOUtils.copy(in, response.getOutputStream());
                } else {
                    try {
                        throw new Exception("ResponseCode=" + conn.getResponseCode());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                String urlString = this.baseURL + pathInfo + "?" + this.getParams(req);
                logger.info(urlString);
                URL url = new URL(urlString);
                InputStream input = url.openStream();
                IOUtils.copy(input, response.getOutputStream());
            }
        } else {
            chain.doFilter(req, res);
        }
    }
}

From source file:ee.ria.xroad.proxy.clientproxy.WsdlRequestProcessor.java

HttpURLConnection createConnection(SoapMessageImpl message) throws Exception {
    URL url = new URL("http://127.0.0.1:" + SystemProperties.getClientProxyHttpPort());

    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setDoInput(true);//from  ww  w.ja  v a2  s. c  o m
    con.setDoOutput(true);
    // Use the same timeouts as client proxy to server proxy connections.
    con.setConnectTimeout(SystemProperties.getClientProxyTimeout());
    con.setReadTimeout(SystemProperties.getClientProxyHttpClientTimeout());
    con.setRequestMethod("POST");

    con.setRequestProperty(HttpHeaders.CONTENT_TYPE,
            MimeUtils.contentTypeWithCharset(MimeTypes.TEXT_XML, StandardCharsets.UTF_8.name()));

    IOUtils.write(message.getBytes(), con.getOutputStream());

    if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
        throw new RuntimeException(
                "Received HTTP error: " + con.getResponseCode() + " - " + con.getResponseMessage());
    }

    return con;
}