Example usage for java.net HttpURLConnection setConnectTimeout

List of usage examples for java.net HttpURLConnection setConnectTimeout

Introduction

In this page you can find the example usage for java.net HttpURLConnection setConnectTimeout.

Prototype

public void setConnectTimeout(int timeout) 

Source Link

Document

Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced by this URLConnection.

Usage

From source file:be.wimsymons.intellij.polopolyimport.PPImporter.java

private void postData(final String name, final Reader reader, final String contentType,
        final String extraParams) throws IOException {
    Writer writer = null;//from  w w w . j  a v a 2 s .  c  om
    LOGGER.info("Doing HTTP POST for " + name);
    try {
        URL httpURL = buildURL(target, extraParams);

        HttpURLConnection httpConnection = (HttpURLConnection) httpURL.openConnection();
        httpConnection.setDoInput(true);
        httpConnection.setDoOutput(true);
        httpConnection.setUseCaches(false);
        httpConnection.setRequestMethod("PUT");
        httpConnection.setRequestProperty("Content-Type", contentType);
        httpConnection.setConnectTimeout(2000);
        httpConnection.setReadTimeout(60000);
        httpConnection.connect();

        if (contentType.contains("UTF-8")) {
            copyAndFlush(reader, httpConnection.getOutputStream());
        } else {
            writer = new OutputStreamWriter(httpConnection.getOutputStream());
            CharStreams.copy(reader, writer);
            writer.flush();
        }

        int responseCode = httpConnection.getResponseCode();
        String responseMessage = httpConnection.getResponseMessage();
        if (responseCode < 200 || responseCode >= 300) {
            failureCount++;
            PPImportPlugin.doNotify("Import of " + name + " failed: " + responseCode + " - " + responseMessage
                    + "\nCheck the server log for more details.", NotificationType.ERROR);
        } else {
            successCount++;
        }
    } catch (IOException e) {
        failureCount++;
        PPImportPlugin.doNotify("Import of " + name + " failed: " + e.getMessage(), NotificationType.ERROR);
    } finally {
        Closeables.close(reader, true);
        Closeables.close(writer, true);
    }
}

From source file:es.tekniker.framework.ktek.questionnaire.mng.server.OrionContextBrokerClient.java

private HttpURLConnection getOrionContextBrokerGEConnection(String method, String service, String contentType) {
    HttpURLConnection conn = null;
    URL url = null;/*from   w w w. j  a v a 2  s.  co m*/

    String urlStr = this.protocol + "://" + service + method;
    log.debug(urlStr);
    try {
        url = new URL(urlStr);
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod(this.methodPOST);
        conn.setRequestProperty(this.headerContentType, contentType);
        conn.setConnectTimeout(this.timeout);

        log.debug(this.headerContentType + " " + contentType);
    } catch (MalformedURLException e) {
        log.error("MalformedURLException " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        log.error("IOException " + e.getMessage());
        e.printStackTrace();
    }
    return conn;
}

From source file:com.polyvi.xface.extension.advancedfiletransfer.FileUploader.java

/**
 * ?urlhttp/* w  ww .  j  a v a  2 s. c o m*/
 *
 * @param url
 *            :url?
 * @return urlhttp
 * */
private HttpURLConnection getHttpConnection(String url)
        throws IOException, MalformedURLException, ProtocolException {
    HttpURLConnection httpConnection;
    httpConnection = ((HttpURLConnection) new URL(url).openConnection());
    httpConnection.setConnectTimeout(mTimeout);
    httpConnection.setRequestMethod("POST");
    httpConnection.setDoInput(true);
    httpConnection.setDoOutput(true);
    return httpConnection;
}

From source file:net.kourlas.voipms_sms.Api.java

private JSONObject getJson(String urlString) {
    try {/*from www . j a  va 2  s .c o m*/
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(10000);
        connection.setConnectTimeout(15000);
        connection.setRequestMethod("GET");
        connection.setDoInput(true);
        connection.connect();

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        StringBuilder data = new StringBuilder();
        String newLine = System.getProperty("line.separator");
        String line;
        while ((line = reader.readLine()) != null) {
            data.append(line);
            data.append(newLine);
        }
        reader.close();

        return new JSONObject(data.toString());
    } catch (MalformedURLException ex) {
        return null;
    } catch (IOException ex) {
        return null;
    } catch (JSONException ex) {
        return null;
    }
}

From source file:dssat.WeatherFileSystem.java

public String WriteToFile(String wthFileName) {

    // prepare the file name from the organization name and the site index number and then write to that file
    String orgName = incache.get("Farm");
    String siteIndex = incache.get("SiteIndex");
    String finalOutputPath = readAttribute("DssatFolder");
    finalOutputPath = finalOutputPath + "\\" + readAttribute("Crop");

    File file = new File(finalOutputPath + dirseprator + wthFileName);

    String writeBuffer = null;/*w w  w.  j  av  a2  s.  c om*/

    PrintWriter pr = null;
    try {
        file.createNewFile();
        pr = new PrintWriter(file);
        writeBuffer = new String("*WEATHER : \n");
        pr.println(writeBuffer);
        writeBuffer = new String("@ INSI      LAT     LONG  ELEV   TAV   AMP REFHT WNDHT");
        pr.println(writeBuffer);

        double latitude = -34.23;
        double longitude = -34.23;
        double elevation = -99;
        double tavg = -99;
        double tamp = -99;
        double tmht = -99;
        double wmht = -99;

        writeBuffer = new String();
        //Empty 2 Char, Org 2 Char, Site 2Char, Space 1 Char, latitude 8Chars with 3 dec
        writeBuffer = String.format(
                "%.2s%.2s%.2s%.1s%8.3f%.1s%8.3f%.1s%5.0f%.1s%5.1f%.1s%5.1f%.1s%5.1f%.1s%5.1f", "  ", orgName,
                siteIndex, " ", latitude, " ", longitude, " ", elevation, " ", tavg, " ", tamp, " ", tmht, " ",
                wmht);
        pr.println(writeBuffer);

        int julianday = 56001;
        double solarrad = -99;
        double tmax = -99;
        double tmin = -99;
        double rain = -99;
        double dewp = -99;
        double wind = -99;
        double par = -99;

        writeBuffer = new String("@DATE  SRAD  TMAX  TMIN  RAIN  RHUM  WIND  TDEW  PAR");
        pr.println(writeBuffer);
        writeBuffer = new String();

        URL url = null;
        InputStream is = null;
        Integer plantingyear;
        if (incache.get("PlantingYear") != null) {
            plantingyear = Integer.parseInt(incache.get("PlantingYear"));
        } else {
            Date d = new Date();
            plantingyear = d.getYear() + 1900;
        }
        /*Bring the Weather details for last 10 Years and write the details to the WTH File. */
        try {

            String query = new String("SELECT%20*%20FROM%20FAWN_historic_daily_20140212%20"
                    + "WHERE%20(%20yyyy%20BETWEEN%20" + (plantingyear - 10) + "%20AND%20"
                    + plantingyear.toString() + ")" + "%20AND%20(%20LocId%20=%20"
                    + incache.get("StationLocationId") + ")" + "%20ORDER%20BY%20yyyy%20DESC%20");

            String urlStr = "http://abe.ufl.edu/bmpmodel/xmlread/rohit.php?sql=" + query;

            System.out.println("********************************");
            System.out.println(urlStr);

            //System.out.println(urlStr);
            URL uflconnection = new URL(urlStr);
            HttpURLConnection huc = (HttpURLConnection) uflconnection.openConnection();
            HttpURLConnection.setFollowRedirects(false);
            huc.setConnectTimeout(15 * 1000);
            huc.setRequestMethod("GET");
            huc.connect();
            InputStream input = huc.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                if (!(inputLine.startsWith("S") || inputLine.startsWith("s"))) {
                    String[] fields = inputLine.split(",");

                    int M = Integer.parseInt(fields[3]);
                    int D = Integer.parseInt(fields[4]);
                    int a = (14 - M) / 12;
                    int y = Integer.parseInt(fields[2]) + 4800 - a;
                    int m = M + 12 * a - 3;

                    long JD = D + (153 * m + 2) / 5 + 365 * y + y / 4 - y / 100 + y / 400 - 32045;

                    String tempDate = String.format("%05d",
                            Integer.parseInt(fields[2].substring(2)) * 1000 + Integer.parseInt(fields[5]));
                    String SRad;
                    if (fields[13].length() > 1) {
                        SRad = String.format("%.1f", Double.parseDouble(fields[13]));
                    } else {
                        SRad = "";
                    }
                    String TMax = String.format("%.1f", Double.parseDouble(fields[9]));
                    String TMin = String.format("%.1f", Double.parseDouble(fields[8]));
                    String RAIN = String.format("%.1f", Double.parseDouble(fields[12]));
                    String RHUM = String.format("%.1f", Double.parseDouble(fields[11]));
                    String WIND = String.format("%.1f", Double.parseDouble(fields[14]));
                    String TDEW = String.format("%.1f", Double.parseDouble(fields[10]));
                    String PAR = "";

                    String line = String.format("%5s %5s %5s %5s %5s %5s %5s %5s", tempDate, SRad, TMax, TMin,
                            RAIN, RHUM, WIND, TDEW);
                    pr.println(line);

                }
            }
            in.close();
            //System.out.println("Created teh connection successfully");

        } catch (MalformedURLException me) {
            me.printStackTrace();
            //return 21.4;
        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {

        if (pr != null) {
            pr.close();
        }
    }

    // Here I need to read all the data from the controls and write the data to the files. 
    for (int i = 0; i < incache.size(); i++) {

    }
    return file.getAbsolutePath();
}

From source file:com.jacr.instagramtrendreader.Main.java

private boolean isOnline(int timeout) {
    // Test 1: Is GPRS / Wifi port ON?
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnected()) {
        try {//  w w w  .  j  av  a2 s.  co  m
            // Test 2: Ping specific url
            URL url = new URL("http://www.google.com");
            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setConnectTimeout(timeout);
            urlc.connect();
            if (urlc.getResponseCode() == HttpURLConnection.HTTP_OK) {
                return true;
            }
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return false;
}

From source file:com.yahoo.druid.hadoop.HiveDatasourceInputFormat.java

private String getSegmentsToLoad(String dataSource, List<Interval> intervals, String overlordUrl)
        throws MalformedURLException {
    logger.info("CheckPost7");
    String urlStr = "http://" + overlordUrl + "/druid/indexer/v1/action";
    logger.info("Sending request to overlord at " + urlStr);

    Interval interval = intervals.get(0);

    String requestJson = getSegmentListUsedActionJson(interval.toString());
    logger.info("request json is " + requestJson);

    int numTries = 3;
    for (int trial = 0; trial < numTries; trial++) {
        try {// w  ww  .  ja  v  a  2s .co m
            logger.info("attempt number {} to get list of segments from overlord", trial);
            Proxy proxy = new Proxy(Proxy.Type.HTTP,
                    new InetSocketAddress("httpproxy-prod.blue.ygrid.yahoo.com", 4080));
            URL url = new URL(String.format("%s/druid/coordinator/v1/metadata/datasources/%s/segments?full",
                    overlordUrl, dataSource));
            //new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("content-type", "application/json");
            conn.setRequestProperty("Accept", "*/*");
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setConnectTimeout(60000);
            conn.usingProxy();
            OutputStream out = conn.getOutputStream();
            out.write(requestJson.getBytes());
            out.close();
            int responseCode = conn.getResponseCode();
            if (responseCode == 200) {
                return IOUtils.toString(conn.getInputStream());
            } else {
                logger.warn(
                        "Attempt Failed to get list of segments from overlord. response code [%s] , response [%s]",
                        responseCode, IOUtils.toString(conn.getInputStream()));
            }
        } catch (Exception ex) {
            logger.warn("Exception in getting list of segments from overlord", ex);
        }

        try {
            Thread.sleep(5000); //wait before next trial
        } catch (InterruptedException ex) {
            Throwables.propagate(ex);
        }
    }

    throw new RuntimeException(
            String.format("failed to find list of segments, dataSource[%s], interval[%s], overlord[%s]",
                    dataSource, interval, overlordUrl));
}

From source file:com.workfront.api.StreamClient.java

private HttpURLConnection createConnection(String spec, String method) throws IOException {
    URL url = new URL(spec);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    if (conn instanceof HttpsURLConnection) {
        ((HttpsURLConnection) conn).setHostnameVerifier(HOSTNAME_VERIFIER);
    }//from   w ww  .  j av a  2 s .  co m

    conn.setAllowUserInteraction(false);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setConnectTimeout(60000);
    conn.setReadTimeout(300000);

    return conn;
}

From source file:net.kervala.comicsreader.BrowseRemoteAlbumsTask.java

@Override
protected String doInBackground(String... params) {
    String error = null;//from  www.j a  va2s  .c om

    URL url = null;

    try {
        // open a stream on URL
        url = new URL(mUrl);
    } catch (MalformedURLException e) {
        error = e.toString();
        e.printStackTrace();
    }

    boolean retry = false;
    HttpURLConnection urlConnection = null;
    int resCode = 0;

    do {
        // create the new connection
        ComicsAuthenticator.sInstance.reset();

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

        try {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(ComicsParameters.TIME_OUT);
            urlConnection.setReadTimeout(ComicsParameters.TIME_OUT);
            resCode = urlConnection.getResponseCode();
        } catch (EOFException e) {
            // under Android 4
            resCode = -1;
        } catch (IOException e) {
            e.printStackTrace();
        }

        Log.d("ComicsReader", "Rescode " + resCode);

        if (resCode < 0) {
            retry = true;
        } else if (resCode == 401) {
            ComicsAuthenticator.sInstance.setResult(false);

            // user pressed cancel
            if (!ComicsAuthenticator.sInstance.isValidated()) {
                return null;
            }

            retry = true;
        } else {
            retry = false;
        }
    } while (retry);

    if (resCode != HttpURLConnection.HTTP_OK) {
        ComicsAuthenticator.sInstance.setResult(false);

        // TODO: HTTP error occurred 
        return null;
    }

    final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    InputStream is = null;

    try {
        // download the file
        is = new BufferedInputStream(urlConnection.getInputStream(), ComicsParameters.BUFFER_SIZE);

        int count = 0;
        byte data[] = new byte[ComicsParameters.BUFFER_SIZE];

        while ((count = is.read(data)) != -1) {
            bytes.write(data, 0, count);
        }

        ComicsAuthenticator.sInstance.setResult(true);
    } catch (IOException e) {
        error = e.toString();
        e.printStackTrace();
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

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

    if (bytes != null) {
        final String text = new String(bytes.toByteArray());

        if (text.contains("<albums>")) {
            parseXml(text);
        } else if (text.contains("\"albums\":")) {
            parseJson(text);
        } else {
            Log.e("ComicsReader", "Error");
        }
    }

    return error;
}

From source file:com.skelril.ShivtrAuth.AuthenticationCore.java

public synchronized JSONArray getFrom(String subAddress) {

    JSONArray objective = new JSONArray();
    HttpURLConnection connection = null;
    BufferedReader reader = null;

    try {//  w w w .  j a  v  a 2 s .co  m
        JSONParser parser = new JSONParser();
        for (int i = 1; true; i++) {

            try {
                // Establish the connection
                URL url = new URL(websiteURL + subAddress + "?page=" + i);
                connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(1500);
                connection.setReadTimeout(1500);

                // Check response codes return if invalid
                if (connection.getResponseCode() < 200 || connection.getResponseCode() >= 300)
                    return null;

                // Begin to read results
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder builder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }

                // Parse Data
                JSONObject o = (JSONObject) parser.parse(builder.toString());
                JSONArray ao = (JSONArray) o.get("characters");
                if (ao.isEmpty())
                    break;
                Collections.addAll(objective, (JSONObject[]) ao.toArray(new JSONObject[ao.size()]));
            } catch (ParseException e) {
                break;
            } finally {
                if (connection != null)
                    connection.disconnect();

                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException ignored) {
                    }
                }
            }
        }
    } catch (IOException e) {
        return null;
    }

    return objective;
}