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.conx.logistics.kernel.bpm.impl.jbpm.core.mock.BPMGuvnorUtil.java

private InputStream getInputStreamForURL(String urlLocation, String requestMethod) throws Exception {
    URL url = new URL(urlLocation);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    connection.setRequestMethod(requestMethod);
    connection.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16");
    connection.setRequestProperty("Accept", "text/plain,text/html,application/xhtml+xml,application/xml");
    connection.setRequestProperty("charset", "UTF-8");
    connection.setConnectTimeout(Integer.parseInt(getGuvnorConnectTimeout()));
    connection.setReadTimeout(Integer.parseInt(getGuvnorReadTimeout()));
    applyAuth(connection);//  w w  w. jav a 2  s . c o m
    connection.connect();

    BufferedReader sreader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
    StringBuilder stringBuilder = new StringBuilder();

    String line = null;
    while ((line = sreader.readLine()) != null) {
        stringBuilder.append(line + "\n");
    }

    return new ByteArrayInputStream(stringBuilder.toString().getBytes("UTF-8"));
}

From source file:com.p2p.misc.DeviceUtility.java

private Boolean RqsLocation(int cid, int lac) {

    Boolean result = false;/*from www.j a  va2s.  c o m*/

    String urlmmap = "http://www.google.com/glm/mmap";

    try {
        if (simPresent() == 1) {
            if (!inAirplaneMode()) {
                if (CheckNetConnectivity(mactivity)) {
                    URL url = new URL(urlmmap);
                    URLConnection conn = url.openConnection();
                    HttpURLConnection httpConn = (HttpURLConnection) conn;
                    httpConn.setRequestMethod("POST");
                    httpConn.setDoOutput(true);
                    httpConn.setDoInput(true);
                    httpConn.setReadTimeout(60000);
                    httpConn.connect();

                    OutputStream outputStream = httpConn.getOutputStream();
                    WriteData(outputStream, cid, lac);

                    InputStream inputStream = httpConn.getInputStream();
                    DataInputStream dataInputStream = new DataInputStream(inputStream);

                    dataInputStream.readShort();
                    dataInputStream.readByte();
                    int code = dataInputStream.readInt();
                    System.out.println("code--->>" + code);
                    if (code == 0) {
                        myLatitude = dataInputStream.readInt();
                        myLongitude = dataInputStream.readInt();
                        System.out.println("myLatitude--->>" + myLatitude);
                        System.out.println("myLongitude--->>" + myLongitude);
                        result = true;

                    } else {
                        OpenCellID opencellid = new OpenCellID();
                        try {
                            opencellid.GetOpenCellID();
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    } catch (ProtocolException e) {
        // TODO: handle exception
        System.out.println("In Protocol Exception");
        latitude = "0";
        longitude = "0";
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.out.println("In IO Exception");
        latitude = "0";
        longitude = "0";
    }

    return result;

}

From source file:utility.DeviceUtility.java

private Boolean RqsLocation(int cid, int lac) {

    Boolean result = false;// w  w  w .jav  a 2  s. c om

    String urlmmap = "http://www.google.com/glm/mmap";

    try {
        if (simPresent() == 1) {
            if (!inAirplaneMode()) {
                if (CheckNetConnectivity(mactivity)) {
                    URL url = new URL(urlmmap);
                    URLConnection conn = url.openConnection();
                    HttpURLConnection httpConn = (HttpURLConnection) conn;
                    httpConn.setRequestMethod("POST");
                    httpConn.setDoOutput(true);
                    httpConn.setDoInput(true);
                    httpConn.setReadTimeout(60000);
                    httpConn.connect();

                    OutputStream outputStream = httpConn.getOutputStream();
                    WriteData(outputStream, cid, lac);

                    InputStream inputStream = httpConn.getInputStream();
                    DataInputStream dataInputStream = new DataInputStream(inputStream);

                    dataInputStream.readShort();
                    dataInputStream.readByte();
                    int code = dataInputStream.readInt();
                    System.out.println("code--->>" + code);
                    if (code == 0) {
                        myLatitude = dataInputStream.readInt();
                        myLongitude = dataInputStream.readInt();
                        System.out.println("myLatitude--->>" + myLatitude);
                        System.out.println("myLongitude--->>" + myLongitude);
                        result = true;

                    }
                    /*else
                    {
                    OpenCellID opencellid=new OpenCellID();
                    try {
                    opencellid.GetOpenCellID();
                    } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    }
                    }*/
                }
            }
        }
    } catch (ProtocolException e) {
        // TODO: handle exception
        System.out.println("In Protocol Exception");
        latitude = "0";
        longitude = "0";
    }

    catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.out.println("In IO Exception");
        latitude = "0";
        longitude = "0";
    }

    return result;

}

From source file:com.flyingspaniel.nava.request.Request.java

protected HttpURLConnection prepareConnection(HttpURLConnection conn) {
    conn.setRequestProperty(ACCEPT_CHARSET, options.getString("acceptCharset", URLEncoding.UTF8_CHARSET));
    conn.setInstanceFollowRedirects(options.getBoolean("followRedirect", true));
    conn.setUseCaches(options.getBoolean("useCaches", true));

    doAuth(conn);//w ww . j a  va 2  s .  co m
    headersMMap.applyHeadersToConnection(conn);

    int timeout = options.getInt("timeout", 2000);
    conn.setConnectTimeout(timeout);
    conn.setReadTimeout(options.getInt("readTimeout", timeout));

    conn.setDoInput(method.doesInput());
    conn.setDoOutput(method.doesOutput());

    // Since HTTPMethod is an enum with an acceptable protocol, this exception "cannot happen"
    try {
        conn.setRequestMethod(method.getMethodName());
    } catch (ProtocolException e) {
        throw new RuntimeException(e); // cannot happen
    }

    return conn;
}

From source file:com.roamprocess1.roaming4world.syncadapter.SyncAdapter.java

/**
 * Given a string representation of a URL, sets up a connection and gets an input stream.
 *//*  ww w . jav  a 2  s. c  o m*/
private InputStream downloadUrl(final URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(NET_READ_TIMEOUT_MILLIS /* milliseconds */);
    conn.setConnectTimeout(NET_CONNECT_TIMEOUT_MILLIS /* milliseconds */);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    // Starts the query
    conn.connect();
    return conn.getInputStream();
}

From source file:com.mendhak.gpslogger.senders.googledrive.GoogleDriveJob.java

private String updateFileContents(String authToken, String gpxFileId, byte[] fileContents, String fileName) {
    HttpURLConnection conn = null;
    String fileId = null;// ww  w .j a v a2  s .  c om

    String fileUpdateUrl = "https://www.googleapis.com/upload/drive/v2/files/" + gpxFileId
            + "?uploadType=media";

    try {

        URL url = new URL(fileUpdateUrl);

        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("PUT");
        conn.setRequestProperty("User-Agent", "GPSLogger for Android");
        conn.setRequestProperty("Authorization", "Bearer " + authToken);
        conn.setRequestProperty("Content-Type", getMimeTypeFromFileName(fileName));
        conn.setRequestProperty("Content-Length", String.valueOf(fileContents.length));

        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setConnectTimeout(10000);
        conn.setReadTimeout(30000);

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.write(fileContents);
        wr.flush();
        wr.close();

        String fileMetadata = Streams.getStringFromInputStream(conn.getInputStream());

        JSONObject fileMetadataJson = new JSONObject(fileMetadata);
        fileId = fileMetadataJson.getString("id");
        LOG.debug("File updated : " + fileId);

    } catch (Exception e) {
        LOG.error("Could not update contents", e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    return fileId;
}

From source file:net.andylizi.colormotd.Updater.java

private boolean checkUpdate() {
    if (file != null && file.exists()) {
        cancel();/*from w  ww . j  a  v a2s.  co m*/
    }
    URL url;
    try {
        url = new URL(UPDATE_URL);
    } catch (MalformedURLException ex) {
        if (DEBUG) {
            ex.printStackTrace();
        }
        return false;
    }
    try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setUseCaches(false);
        conn.setRequestMethod("GET");
        conn.addRequestProperty("User-Agent", userAgent);
        if (etag != null) {
            conn.addRequestProperty("If-None-Match", etag);
        }
        conn.addRequestProperty("Accept", "application/json,text/plain,*/*;charset=utf-8");
        conn.addRequestProperty("Accept-Encoding", "gzip");
        conn.addRequestProperty("Cache-Control", "no-cache");
        conn.addRequestProperty("Date", new Date().toString());
        conn.addRequestProperty("Connection", "close");

        conn.setDoInput(true);
        conn.setDoOutput(false);
        conn.setConnectTimeout(2000);
        conn.setReadTimeout(2000);

        conn.connect();

        if (conn.getHeaderField("ETag") != null) {
            etag = conn.getHeaderField("ETag");
        }
        if (DEBUG) {
            logger.log(Level.INFO, "DEBUG ResponseCode: {0}", conn.getResponseCode());
            logger.log(Level.INFO, "DEBUG ETag: {0}", etag);
        }
        if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
            return false;
        } else if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return false;
        }

        BufferedReader input = null;
        if (conn.getContentEncoding() != null && conn.getContentEncoding().contains("gzip")) {
            input = new BufferedReader(
                    new InputStreamReader(new GZIPInputStream(conn.getInputStream()), "UTF-8"), 1);
        } else {
            input = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"), 1);
        }

        StringBuilder builder = new StringBuilder();
        String buffer = null;
        while ((buffer = input.readLine()) != null) {
            builder.append(buffer);
        }
        try {
            JSONObject jsonObj = (JSONObject) new JSONParser().parse(builder.toString());
            int build = ((Number) jsonObj.get("build")).intValue();
            if (build <= ColorMOTD.buildVersion) {
                return false;
            }
            String version = (String) jsonObj.get("version");
            String msg = (String) jsonObj.get("msg");
            String download_url = (String) jsonObj.get("url");
            newVersion = new NewVersion(version, build, msg, download_url);
            return true;
        } catch (ParseException ex) {
            if (DEBUG) {
                ex.printStackTrace();
            }
            exception = ex;
            return false;
        }
    } catch (SocketTimeoutException ex) {
        return false;
    } catch (IOException ex) {
        if (DEBUG) {
            ex.printStackTrace();
        }
        exception = ex;
        return false;
    }
}

From source file:com.truebanana.http.HTTPRequest.java

private HttpURLConnection buildURLConnection() {
    try {/*from   ww  w  . j a  va  2 s  .c om*/
        Uri.Builder builder = Uri.parse(url).buildUpon();
        Iterator<Map.Entry<String, String>> iterator = queryParameters.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> pair = (Map.Entry) iterator.next();
            builder.appendQueryParameter(pair.getKey(), pair.getValue());
        }

        URL u = new URL(builder.build().toString());

        Proxy proxy = Proxy.NO_PROXY;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR1) {
            String host = System.getProperty("http.proxyHost");
            if (host != null && !host.isEmpty()) {
                String port = System.getProperty("http.proxyPort");
                if (port != null && !port.isEmpty()) {
                    proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, Integer.parseInt(port)));
                }
            }
        }

        HttpURLConnection urlConnection = (HttpURLConnection) u.openConnection(proxy);
        urlConnection.setRequestMethod(requestMethod.name());
        urlConnection.setDoInput(true);
        urlConnection.setConnectTimeout(connectTimeout);
        urlConnection.setReadTimeout(readTimeout);

        switch (requestMethod) {
        case POST:
        case PUT:
            urlConnection.setDoOutput(true);
            break;
        default:
        case GET:
        case DELETE:
            urlConnection.setDoOutput(false);
            break;
        }
        return urlConnection;
    } catch (MalformedURLException e) {
        e.printStackTrace();
        throw new IllegalArgumentException("Invalid URL.");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalArgumentException("Invalid URL.");
    }
}

From source file:net.andylizi.colormotd.anim.updater.Updater.java

private boolean checkUpdate() {
    if (new File(Bukkit.getUpdateFolderFile(), fileName).exists()) {
        cancel();//from w w  w  .  j av  a2 s .  co  m
    }
    URL url;
    try {
        url = new URL(UPDATE_URL);
    } catch (MalformedURLException ex) {
        if (DEBUG) {
            ex.printStackTrace();
        }
        return false;
    }
    try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setUseCaches(false);
        conn.setRequestMethod("GET");
        conn.addRequestProperty("User-Agent", USER_AGENT);
        if (etag != null) {
            conn.addRequestProperty("If-None-Match", etag);
        }
        conn.addRequestProperty("Accept", "application/json,text/plain,*/*;charset=utf-8");
        conn.addRequestProperty("Accept-Encoding", "gzip");
        conn.addRequestProperty("Cache-Control", "no-cache");
        conn.addRequestProperty("Date", new Date().toString());
        conn.addRequestProperty("Connection", "close");

        conn.setDoInput(true);
        conn.setDoOutput(false);
        conn.setConnectTimeout(2000);
        conn.setReadTimeout(2000);

        conn.connect();

        if (conn.getHeaderField("ETag") != null) {
            etag = conn.getHeaderField("ETag");
        }
        if (DEBUG) {
            logger.log(Level.INFO, "DEBUG ResponseCode: {0}", conn.getResponseCode());
            logger.log(Level.INFO, "DEBUG ETag: {0}", etag);
        }
        if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
            return false;
        } else if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return false;
        }

        BufferedReader input = null;
        if (conn.getContentEncoding() != null && conn.getContentEncoding().contains("gzip")) {
            input = new BufferedReader(
                    new InputStreamReader(new GZIPInputStream(conn.getInputStream()), "UTF-8"), 1);
        } else {
            input = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"), 1);
        }

        StringBuilder builder = new StringBuilder();
        String buffer = null;
        while ((buffer = input.readLine()) != null) {
            builder.append(buffer);
        }
        try {
            JSONObject jsonObj = (JSONObject) new JSONParser().parse(builder.toString());
            int build = ((Number) jsonObj.get("build")).intValue();
            if (build <= buildVersion) {
                return false;
            }
            String version = (String) jsonObj.get("version");
            String msg = (String) jsonObj.get("msg");
            String download_url = (String) jsonObj.get("url");
            newVersion = new NewVersion(version, build, msg, download_url);
            return true;
        } catch (ParseException ex) {
            if (DEBUG) {
                ex.printStackTrace();
            }
            exception = ex;
            return false;
        }
    } catch (SocketTimeoutException ex) {
        return false;
    } catch (IOException ex) {
        if (DEBUG) {
            ex.printStackTrace();
        }
        exception = ex;
        return false;
    }
}