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.diablominer.DiabloMiner.NetworkState.JSONRPCNetworkState.java

JsonNode doJSONRPCCall(boolean longPoll, ObjectNode message) throws IOException {
    HttpURLConnection connection = null;
    try {/*from w w  w .j  a va 2  s.  c om*/
        URL url;

        if (longPoll)
            url = longPollUrl;
        else
            url = queryUrl;

        Proxy proxy = diabloMiner.getProxy();

        if (proxy == null)
            connection = (HttpURLConnection) url.openConnection();
        else
            connection = (HttpURLConnection) url.openConnection(proxy);

        if (longPoll) {
            connection.setConnectTimeout(10 * 60 * 1000);
            connection.setReadTimeout(10 * 60 * 1000);
        } else {
            connection.setConnectTimeout(15 * 1000);
            connection.setReadTimeout(15 * 1000);
        }

        connection.setRequestProperty("Authorization", userPass);
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Accept-Encoding", "gzip,deflate");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Cache-Control", "no-cache");
        connection.setRequestProperty("User-Agent", "DiabloMiner");
        connection.setRequestProperty("X-Mining-Extensions", "longpoll rollntime switchto");
        connection.setDoOutput(true);

        OutputStream requestStream = connection.getOutputStream();
        Writer request = new OutputStreamWriter(requestStream);
        request.write(message.toString());
        request.close();
        requestStream.close();

        ObjectNode responseMessage = null;

        InputStream responseStream = null;

        try {
            String xLongPolling = connection.getHeaderField("X-Long-Polling");

            if (xLongPolling != null && !"".equals(xLongPolling) && longPollAsync == null) {
                if (xLongPolling.startsWith("http"))
                    longPollUrl = new URL(xLongPolling);
                else if (xLongPolling.startsWith("/"))
                    longPollUrl = new URL(queryUrl.getProtocol(), queryUrl.getHost(), queryUrl.getPort(),
                            xLongPolling);
                else
                    longPollUrl = new URL(queryUrl.getProtocol(), queryUrl.getHost(), queryUrl.getPort(),
                            (url.getFile() + "/" + xLongPolling).replace("//", "/"));

                longPollAsync = new LongPollAsync();
                Thread thread = new Thread(longPollAsync,
                        "DiabloMiner JSONRPC LongPollAsync for " + url.getHost());
                thread.start();
                diabloMiner.addThread(thread);

                workLifetime = 60000;

                diabloMiner.debug(queryUrl.getHost() + ": Enabling long poll support");
            }

            String xRollNTime = connection.getHeaderField("X-Roll-NTime");

            if (xRollNTime != null && !"".equals(xRollNTime)) {
                if (!"n".equalsIgnoreCase(xRollNTime) && rollNTime == false) {
                    rollNTime = true;

                    if (xRollNTime.startsWith("expire=")) {
                        try {
                            workLifetime = Integer.parseInt(xRollNTime.substring(7)) * 1000;
                        } catch (NumberFormatException ex) {
                        }
                    } else {
                        workLifetime = 60000;
                    }

                    diabloMiner.debug(queryUrl.getHost() + ": Enabling roll ntime support, expire after "
                            + (workLifetime / 1000) + " seconds");
                } else if ("n".equalsIgnoreCase(xRollNTime) && rollNTime == true) {
                    rollNTime = false;

                    if (longPoll)
                        workLifetime = 60000;
                    else
                        workLifetime = diabloMiner.getWorkLifetime();

                    diabloMiner.debug(queryUrl.getHost() + ": Disabling roll ntime support");
                }
            }

            String xSwitchTo = connection.getHeaderField("X-Switch-To");

            if (xSwitchTo != null && !"".equals(xSwitchTo)) {
                String oldHost = queryUrl.getHost();
                JsonNode newHost = mapper.readTree(xSwitchTo);

                queryUrl = new URL(queryUrl.getProtocol(), newHost.get("host").asText(),
                        newHost.get("port").getIntValue(), queryUrl.getPath());

                if (longPollUrl != null)
                    longPollUrl = new URL(longPollUrl.getProtocol(), newHost.get("host").asText(),
                            newHost.get("port").getIntValue(), longPollUrl.getPath());

                diabloMiner.info(oldHost + ": Switched to " + queryUrl.getHost());
            }

            String xRejectReason = connection.getHeaderField("X-Reject-Reason");

            if (xRejectReason != null && !"".equals(xRejectReason)) {
                rejectReason = xRejectReason;
            }

            String xIsP2Pool = connection.getHeaderField("X-Is-P2Pool");

            if (xIsP2Pool != null && !"".equals(xIsP2Pool)) {
                if (!noDelay)
                    diabloMiner.info("P2Pool no delay mode enabled");

                noDelay = true;
            }

            if (connection.getContentEncoding() != null) {
                if (connection.getContentEncoding().equalsIgnoreCase("gzip"))
                    responseStream = new GZIPInputStream(connection.getInputStream());
                else if (connection.getContentEncoding().equalsIgnoreCase("deflate"))
                    responseStream = new InflaterInputStream(connection.getInputStream());
            } else {
                responseStream = connection.getInputStream();
            }

            if (responseStream == null)
                throw new IOException("Drop to error handler");

            Object output = mapper.readTree(responseStream);

            if (NullNode.class.equals(output.getClass())) {
                throw new IOException("Bitcoin returned unparsable JSON");
            } else {
                try {
                    responseMessage = (ObjectNode) output;
                } catch (ClassCastException e) {
                    throw new IOException("Bitcoin returned unparsable JSON");
                }
            }

            responseStream.close();
        } catch (JsonProcessingException e) {
            throw new IOException("Bitcoin returned unparsable JSON");
        } catch (IOException e) {
            InputStream errorStream = null;
            IOException e2 = null;

            if (connection.getErrorStream() == null)
                throw new IOException("Bitcoin disconnected during response: " + connection.getResponseCode()
                        + " " + connection.getResponseMessage());

            if (connection.getContentEncoding() != null) {
                if (connection.getContentEncoding().equalsIgnoreCase("gzip"))
                    errorStream = new GZIPInputStream(connection.getErrorStream());
                else if (connection.getContentEncoding().equalsIgnoreCase("deflate"))
                    errorStream = new InflaterInputStream(connection.getErrorStream());
            } else {
                errorStream = connection.getErrorStream();
            }

            if (errorStream == null)
                throw new IOException("Bitcoin disconnected during response: " + connection.getResponseCode()
                        + " " + connection.getResponseMessage());

            byte[] errorbuf = new byte[8192];

            if (errorStream.read(errorbuf) < 1)
                throw new IOException("Bitcoin returned an error, but with no message");

            String error = new String(errorbuf).trim();

            if (error.startsWith("{")) {
                try {
                    Object output = mapper.readTree(error);

                    if (NullNode.class.equals(output.getClass()))
                        throw new IOException("Bitcoin returned an error message: " + error);
                    else
                        try {
                            responseMessage = (ObjectNode) output;
                        } catch (ClassCastException f) {
                            throw new IOException("Bitcoin returned unparsable JSON");
                        }

                    if (responseMessage.get("error") != null) {
                        if (responseMessage.get("error").get("message") != null
                                && responseMessage.get("error").get("message").asText() != null) {
                            error = responseMessage.get("error").get("message").asText().trim();
                            e2 = new IOException("Bitcoin returned error message: " + error);
                        } else if (responseMessage.get("error").asText() != null) {
                            error = responseMessage.get("error").asText().trim();

                            if (!"null".equals(error) && !"".equals(error))
                                e2 = new IOException("Bitcoin returned an error message: " + error);
                        }
                    }
                } catch (JsonProcessingException f) {
                    e2 = new IOException("Bitcoin returned unparsable JSON");
                }
            } else {
                e2 = new IOException("Bitcoin returned an error message: " + error);
            }

            errorStream.close();

            if (responseStream != null)
                responseStream.close();

            if (e2 == null)
                e2 = new IOException("Bitcoin returned an error, but with no message");

            throw e2;
        }

        if (responseMessage.get("error") != null) {
            if (responseMessage.get("error").get("message") != null
                    && responseMessage.get("error").get("message").asText() != null) {
                String error = responseMessage.get("error").get("message").asText().trim();
                throw new IOException("Bitcoin returned error message: " + error);
            } else if (responseMessage.get("error").asText() != null) {
                String error = responseMessage.get("error").asText().trim();

                if (!"null".equals(error) && !"".equals(error))
                    throw new IOException("Bitcoin returned error message: " + error);
            }
        }

        JsonNode result;

        try {
            result = responseMessage.get("result");
        } catch (Exception e) {
            throw new IOException("Bitcoin returned unparsable JSON");
        }

        if (result == null)
            throw new IOException("Bitcoin did not return a result or an error");

        return result;
    } catch (IOException e) {
        if (connection != null)
            connection.disconnect();

        throw e;
    }
}

From source file:edu.usf.cutr.opentripplanner.android.tasks.RequestTimesForTrips.java

protected HashMap<String, List<TripTimeShort>> doInBackground(String... reqs) {
    String prefix = PreferenceManager.getDefaultSharedPreferences(context)
            .getString(OTPApp.PREFERENCE_KEY_FOLDER_STRUCTURE_PREFIX, OTPApp.FOLDER_STRUCTURE_PREFIX_NEW);
    if (reqs.length <= 1) {
        return null;
    }//w  w w  .  j  ava2 s.com
    HashMap<String, List<TripTimeShort>> timesUpdatesForTrips = new HashMap<String, List<TripTimeShort>>(
            reqs.length - 1);

    HttpURLConnection urlConnection = null;
    List<TripTimeShort> updatedTripTimesList = null;

    try {
        if (mapper == null) {
            mapper = new ObjectMapper();
        }
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        JavaType bikeRentalStationListType = mapper.getTypeFactory().constructCollectionType(List.class,
                TripTimeShort.class);
        for (String tripId : reqs) {
            if (tripId.equals(reqs[0])) {
                continue;
            }
            String encodedTripId = URLEncoder.encode(tripId, Charset.defaultCharset().name());
            String u = reqs[0] + prefix + OTPApp.TRIP_TIMES_UPDATES_LOCATION_BEFORE_ID + encodedTripId
                    + OTPApp.TRIP_TIMES_UPDATES_LOCATION_AFTER_ID;
            URL url = new URL(u);
            Log.d(OTPApp.TAG, "URL: " + u);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setConnectTimeout(OTPApp.HTTP_CONNECTION_TIMEOUT);
            urlConnection.setReadTimeout(OTPApp.HTTP_SOCKET_TIMEOUT);
            updatedTripTimesList = mapper.readValue(urlConnection.getInputStream(), bikeRentalStationListType);
            timesUpdatesForTrips.put(tripId, updatedTripTimesList);
        }
    } catch (IOException e) {
        Log.e(OTPApp.TAG, "Error fetching JSON or XML: " + e);
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }

    return timesUpdatesForTrips;
}

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

private String createEmptyFile(String authToken, String fileName, String mimeType, String parentFolderId) {

    String fileId = null;//from  ww w .  ja  v  a 2 s .c o  m
    HttpURLConnection conn = null;

    String createFileUrl = "https://www.googleapis.com/drive/v2/files";

    String createFilePayload = "   {\n" + "             \"title\": \"" + fileName + "\",\n"
            + "             \"mimeType\": \"" + mimeType + "\",\n" + "             \"parents\": [\n"
            + "              {\n" + "               \"id\": \"" + parentFolderId + "\"\n" + "              }\n"
            + "             ]\n" + "            }";

    try {

        URL url = new URL(createFileUrl);

        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("User-Agent", "GPSLogger for Android");
        conn.setRequestProperty("Authorization", "Bearer " + authToken);
        conn.setRequestProperty("Content-Type", "application/json");

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

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

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(createFilePayload);
        wr.flush();
        wr.close();

        fileId = null;

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

        JSONObject fileMetadataJson = new JSONObject(fileMetadata);
        fileId = fileMetadataJson.getString("id");
        LOG.debug("File created with ID " + fileId + " of type " + mimeType);

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

    }

    return fileId;
}

From source file:com.cgxlib.xq.rebind.JsniBundleGenerator.java

/**
 * Get the content of a javascript source. It supports remote sources hosted in CDN's.
 *///  w  w  w.j  av  a2s .  c o  m
private String getContent(TreeLogger logger, String path, String src) throws UnableToCompleteException {
    HttpURLConnection connection = null;
    InputStream in = null;
    try {
        if (!src.matches("(?i)https?://.*")) {
            String file = path + "/" + src;
            logger.log(TreeLogger.INFO,
                    getClass().getSimpleName() + " - importing external javascript: " + file);

            in = this.getClass().getClassLoader().getResourceAsStream(file);
            if (in == null) {
                logger.log(TreeLogger.ERROR, "Unable to read javascript file: " + file);
            }
        } else {
            logger.log(TreeLogger.INFO,
                    getClass().getSimpleName() + " - downloading external javascript: " + src);
            URL url = new URL(src);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
            connection.setRequestProperty("Host", url.getHost());
            connection.setConnectTimeout(3000);
            connection.setReadTimeout(3000);

            int status = connection.getResponseCode();
            if (status != HttpURLConnection.HTTP_OK) {
                logger.log(TreeLogger.ERROR, "Server Error: " + status + " " + connection.getResponseMessage());
                throw new UnableToCompleteException();
            }

            String encoding = connection.getContentEncoding();
            in = connection.getInputStream();
            if ("gzip".equalsIgnoreCase(encoding)) {
                in = new GZIPInputStream(in);
            } else if ("deflate".equalsIgnoreCase(encoding)) {
                in = new InflaterInputStream(in);
            }
        }

        return inputStreamToString(in);
    } catch (IOException e) {
        logger.log(TreeLogger.ERROR, "Error: " + e.getMessage());
        throw new UnableToCompleteException();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:org.jmxtrans.embedded.output.CopperEggWriter.java

/**
 * If dashboard doesn't exist, create it
 * If it does exist, update it./*from  w  w w. j  ava  2 s. c  o  m*/
 */

private void ensure_dashboards() {
    HttpURLConnection urlConnection = null;
    OutputStreamWriter wr = null;
    URL myurl = null;

    try {
        myurl = new URL(url_str + "/dashboards.json");
        urlConnection = (HttpURLConnection) myurl.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setReadTimeout(coppereggApiTimeoutInMillis);
        urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8");
        urlConnection.setRequestProperty("Authorization", "Basic " + basicAuthentication);

        int responseCode = urlConnection.getResponseCode();
        if (responseCode != 200) {
            logger.warn(
                    "Bad responsecode " + String.valueOf(responseCode) + " from Dahsboards Index: " + myurl);
        }
    } catch (Exception e) {
        exceptionCounter.incrementAndGet();
        logger.warn("Exception on dashboards index request " + myurl + "  " + e);
    } finally {
        if (urlConnection != null) {
            try {
                InputStream in = urlConnection.getInputStream();
                String theString = convertStreamToString(in);
                for (Map.Entry<String, String> entry : dashMap.entrySet()) {
                    String checkName = entry.getKey();
                    try {
                        String Rslt = groupFind(checkName, theString, 1);
                        if (Rslt != null) {
                            // Update it
                            Rslt = Send_Commmand("/dashboards/" + Rslt + ".json", "PUT", entry.getValue(), 1);
                        } else {
                            // create it
                            Rslt = Send_Commmand("/dashboards.json", "POST", entry.getValue(), 1);
                        }
                    } catch (Exception e) {
                        exceptionCounter.incrementAndGet();
                        logger.warn("Exception in dashboard update or create: " + myurl + "  " + e);
                    }
                }
            } catch (IOException e) {
                exceptionCounter.incrementAndGet();
                logger.warn("Exception flushing http connection" + e);
            }
        }
    }
}

From source file:org.jmxtrans.embedded.output.CopperEggWriter.java

/**
 * If metric group doesn't exist, create it
 * If it does exist, update it.//w ww .  j  a va 2s .  c  o m
 */

public void ensure_metric_groups() {
    HttpURLConnection urlConnection = null;
    OutputStreamWriter wr = null;
    URL myurl = null;

    try {
        myurl = new URL(url_str + "/metric_groups.json?show_hidden=1");
        urlConnection = (HttpURLConnection) myurl.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setReadTimeout(coppereggApiTimeoutInMillis);
        urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8");
        urlConnection.setRequestProperty("Authorization", "Basic " + basicAuthentication);

        int responseCode = urlConnection.getResponseCode();
        if (responseCode != 200) {
            logger.warn(
                    "Bad responsecode " + String.valueOf(responseCode) + " from metric_groups Index: " + myurl);
        }
    } catch (Exception e) {
        exceptionCounter.incrementAndGet();
        logger.warn("Failure to execute metric_groups index request " + myurl + "  " + e);
    } finally {
        if (urlConnection != null) {
            try {
                InputStream in = urlConnection.getInputStream();
                String theString = convertStreamToString(in);
                for (Map.Entry<String, String> entry : metricgroupMap.entrySet()) {
                    String checkName = entry.getKey();
                    try {
                        String Rslt = groupFind(checkName, theString, 0);
                        if (Rslt != null) {
                            // Update it
                            Rslt = Send_Commmand("/metric_groups/" + Rslt + ".json?show_hidden=1", "PUT",
                                    entry.getValue(), 0);
                        } else {
                            // create it
                            Rslt = Send_Commmand("/metric_groups.json", "POST", entry.getValue(), 0);
                        }
                        if (Rslt != null) {
                            if (Rslt.toLowerCase().contains("tomcat")) {
                                if (Rslt.toLowerCase().contains("thread_pool")) {
                                    tomcat_thread_pool_groupID = Rslt;
                                } else if (Rslt.toLowerCase().contains("grp")) {
                                    tomcat_grp_groupID = Rslt;
                                } else if (Rslt.toLowerCase().contains("servlet")) {
                                    tomcat_servlet_groupID = Rslt;
                                } else if (Rslt.toLowerCase().contains("manager")) {
                                    tomcat_manager_groupID = Rslt;
                                } else if (Rslt.toLowerCase().contains("db")) {
                                    tomcat_db_groupID = Rslt;
                                }
                            } else if (Rslt.toLowerCase().contains("jmxtrans")) {
                                jmxtrans_metric_groupID = Rslt;
                            } else if (Rslt.toLowerCase().contains("sales")) {
                                app_sales_groupID = Rslt;
                            } else if (Rslt.toLowerCase().contains("cocktail")) {
                                app_groupID = Rslt;
                            } else if (Rslt.toLowerCase().contains("jvm")) {
                                if (Rslt.toLowerCase().contains("os")) {
                                    jvm_os_groupID = Rslt;
                                } else if (Rslt.toLowerCase().contains("gc")) {
                                    jvm_gc_groupID = Rslt;
                                } else if (Rslt.toLowerCase().contains("runtime")) {
                                    jvm_runtime_groupID = Rslt;
                                } else if (Rslt.toLowerCase().contains("class")) {
                                    jvm_class_groupID = Rslt;
                                } else if (Rslt.toLowerCase().contains("thread")) {
                                    jvm_thread_groupID = Rslt;
                                }
                            } else if (Rslt.toLowerCase().contains("nonheap")) {
                                nonheap_metric_groupID = Rslt;
                            } else if (Rslt.toLowerCase().contains("heap")) {
                                heap_metric_groupID = Rslt;
                            }
                        }
                    } catch (Exception e) {
                        exceptionCounter.incrementAndGet();
                        logger.warn("Exception in metric_group update or create: " + myurl + "  " + e);
                    }
                }
            } catch (IOException e) {
                exceptionCounter.incrementAndGet();
                logger.warn("Exception flushing http connection" + e);
            }
        }
    }
}

From source file:org.jmxtrans.embedded.output.CopperEggWriter.java

public String Send_Commmand(String command, String msgtype, String payload, Integer ExpectInt) {
    HttpURLConnection urlConnection = null;
    URL myurl = null;//  w  ww. j  ava 2s  . c om
    OutputStreamWriter wr = null;
    int responseCode = 0;
    String id = null;
    int error = 0;

    try {
        myurl = new URL(url_str + command);
        urlConnection = (HttpURLConnection) myurl.openConnection();
        urlConnection.setRequestMethod(msgtype);
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setReadTimeout(coppereggApiTimeoutInMillis);
        urlConnection.addRequestProperty("User-Agent", "Mozilla/4.76");
        urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8");
        urlConnection.setRequestProperty("Authorization", "Basic " + basicAuthentication);

        wr = new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8");
        wr.write(payload);
        wr.flush();

        responseCode = urlConnection.getResponseCode();
        if (responseCode != 200) {
            logger.warn(
                    "Send Command: Response code " + responseCode + " url is " + myurl + " command " + msgtype);
            error = 1;
        }
    } catch (Exception e) {
        exceptionCounter.incrementAndGet();
        logger.warn("Exception in Send Command: url is " + myurl + " command " + msgtype + "; " + e);
        error = 1;
    } finally {
        if (urlConnection != null) {
            try {
                if (error > 0) {
                    InputStream err = urlConnection.getErrorStream();
                    String errString = convertStreamToString(err);
                    logger.warn("Reported error : " + errString);
                    IoUtils2.closeQuietly(err);
                } else {
                    InputStream in = urlConnection.getInputStream();
                    String theString = convertStreamToString(in);
                    id = jparse(theString, ExpectInt);
                    IoUtils2.closeQuietly(in);
                }
            } catch (IOException e) {
                exceptionCounter.incrementAndGet();
                logger.warn("Exception in Send Command : flushing http connection " + e);
            }
        }
        if (wr != null) {
            try {
                wr.close();
            } catch (IOException e) {
                exceptionCounter.incrementAndGet();
                logger.warn("Exception in Send Command: closing OutputWriter " + e);
            }
        }
    }
    return (id);
}

From source file:tr.edu.gsu.nerwip.retrieval.reader.wikipedia.WikipediaReader.java

/**
 * Reads the source code of the web page at the specified
 * URL.//  w w  w .j a  va2 s.  c  o  m
 * 
 * @param url
 *       Address of the web page to be read.
 * @return
 *       String containing the read HTML source code.
 * 
 * @throws IOException
 *       Problem while accessing the specified URL.
 */
private String manuallyReadUrl(URL url) throws IOException {
    boolean trad = false;

    BufferedReader br = null;

    // open page the traditional way
    if (trad) {
        InputStream is = url.openStream();
        InputStreamReader isr = new InputStreamReader(is);
        br = new BufferedReader(isr);
    }

    // open with more options
    else { // setup connection
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.setReadTimeout(2000);
        connection.setChunkedStreamingMode(0);
        connection.setRequestProperty("Content-Length", "0");
        //         connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
        connection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
        connection.connect();

        // setup input stream
        // part retrieved from http://stackoverflow.com/questions/538999/java-util-scanner-and-wikipedia
        // original author: Marco Beggio
        InputStream is = null;
        String encoding = connection.getContentEncoding();
        if (connection.getContentEncoding() != null && encoding.equals("gzip")) {
            is = new GZIPInputStream(connection.getInputStream());
        } else if (encoding != null && encoding.equals("deflate")) {
            is = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
        } else {
            is = connection.getInputStream();
        }

        // alternative to spot error details            
        //         InputStream is;
        //         if (connection.getResponseCode() != 200) 
        //            is = connection.getErrorStream();
        //         else 
        //            is = connection.getInputStream();

        InputStreamReader isr = new InputStreamReader(is);
        br = new BufferedReader(isr);
    }

    // read page
    StringBuffer sourceCode = new StringBuffer();
    String line = br.readLine();
    while (line != null) {
        sourceCode.append(line + "\n");
        line = br.readLine();
    }

    String result = sourceCode.toString();
    br.close();
    return result;
}

From source file:pt.aptoide.backupapps.data.webservices.ManagerDownloads.java

public EnumServerLoginStatus checkServerConnection(ViewServerLogin serverLogin) {
    Log.d("Aptoide-ManagerDownloads", "checking connection for: " + serverLogin);
    EnumServerLoginStatus status = EnumServerLoginStatus.REPO_SERVICE_UNAVAILABLE;

    String uri = Constants.SCHEME_HTTP_PREFIX + serverLogin.getRepoName() + Constants.DOMAIN_APTOIDE_STORE
            + "v2/info.xml?info=bare&unix=true&order_by=alphabetic&order_direction=ascending&offset=0&range=1";

    //      HttpParams httpParameters = new BasicHttpParams();
    //      HttpConnectionParams.setConnectionTimeout(httpParameters, 120000);
    //      HttpConnectionParams.setSoTimeout(httpParameters, 120000);

    //      DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);

    //      DefaultHttpClient mHttpClient = Threading.getThreadSafeHttpClient();

    //      httpClient.setRedirectHandler(new RedirectHandler() {
    //         public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
    //            return false;
    //         }//from ww w .jav  a2 s.c  o m
    //
    //         public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {
    //            return null;
    //         }
    //      });

    try {
        if (serverLogin.isRepoPrivate()) {
            Log.d("Aptoide-ManagerDownloads", "private repo, username: " + serverLogin.getPrivUsername()
                    + " password: " + serverLogin.getPrivPassword());
            //              URL url = new URL(uri);
            //              httpClient.getCredentialsProvider().setCredentials(
            //                    new AuthScope(url.getHost(), url.getPort()),
            //                    new UsernamePasswordCredentials(serverLogin.getPrivUsername(), serverLogin.getPrivPassword()));
            uri += "&username=" + serverLogin.getPrivUsername() + "&password=" + serverLogin.getPrivPassword();
        }
        Log.d("Aptoide-ManagerDownloads", "uri: " + uri);
        URL endpoint = new URL(uri);
        HttpURLConnection connection = (HttpURLConnection) endpoint.openConnection(); //Careful with UnknownHostException. Throws MalformedURLException, IOException

        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "application/xml");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        connection.setConnectTimeout(Constants.SERVER_CONNECTION_TIMEOUT);
        connection.setReadTimeout(Constants.SERVER_READ_TIMEOUT);

        //           HttpGet httpGet = new HttpGet(uri);

        //         HttpResponse httpResponse = httpClient.execute(httpGet);

        //         Header[] redirect = httpResponse.getHeaders("Location");
        //         if(redirect.length > 0){
        //            String redirectedUri = redirect[0].getValue();
        //
        //            httpGet = null;
        //            httpGet = new HttpGet(redirectedUri);
        //            
        //            if(serverLogin.isRepoPrivate()){
        //                 Log.d("Aptoide-ManagerDownloads", "private repo, username: "+serverLogin.getPrivUsername()+" password: "+serverLogin.getPrivPassword());
        //                 URL redirectedUrl = new URL(redirectedUri);
        //                 httpClient.getCredentialsProvider().setCredentials(
        //                       new AuthScope(redirectedUrl.getHost(), redirectedUrl.getPort()),
        //                       new UsernamePasswordCredentials(serverLogin.getPrivUsername(), serverLogin.getPrivPassword()));
        //              }
        //            
        //            httpResponse = null;
        //            httpResponse = httpClient.execute(httpGet);
        //         }
        status = serviceData.getManagerXml().dom.parseServerConnectionCheckReturn(connection);
        //         int result = httpResponse.getStatusLine().getStatusCode();
        //         Log.d("Aptoide-ManagerDownloads", "HTTP status line: "+httpResponse.getStatusLine());
        //         
        //         if(result == 200){
        //            return EnumServerLoginStatus.SUCCESS;
        //         }else if (result == 401){
        //            return EnumServerLoginStatus.BAD_REPO_PRIVACY_LOGIN;
        //         }else{            
        //            return EnumServerLoginStatus.REPO_SERVICE_UNAVAILABLE;
        //         }
        return status;
        //      } catch (ClientProtocolException e) {
        //         return EnumServerLoginStatus.REPO_SERVICE_UNAVAILABLE;
        //      } catch (IOException e) { 
        //         return EnumServerLoginStatus.REPO_SERVICE_UNAVAILABLE;
        //      } catch (IllegalArgumentException e) { 
        //         return EnumServerLoginStatus.REPO_SERVICE_UNAVAILABLE;
    } catch (Exception e) {
        return EnumServerLoginStatus.REPO_SERVICE_UNAVAILABLE;
    }
}