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:uk.ac.manchester.cs.owl.semspreadsheets.repository.bioportal.BioPortalRepositoryAccessor.java

public String fetchOntologyFormat(String ontologyAcronym) {
    logger.debug("Fetching format for " + ontologyAcronym);
    BioPortalCache cache = BioPortalCache.getInstance();
    String format = cache.getFormat(ontologyAcronym);
    if (format != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("The ontology format for " + ontologyAcronym + " was found in the cache as " + format);
        }//from w  w  w .  j av  a 2 s . c  om
    } else {
        logger.info("The format for " + ontologyAcronym + " not found in cache, fetching");
        try {
            URL url = new URL(BioPortalRepository.ONTOLOGY_LIST + "/" + ontologyAcronym + "/"
                    + BioPortalRepository.LATEST_SUBMISSION + "?format=json&apikey="
                    + BioPortalRepository.readAPIKey());
            logger.info("About to fetch more ontology information from " + url.toExternalForm());
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(CONNECT_TIMEOUT);
            connection.setReadTimeout(CONNECT_TIMEOUT);
            int responseCode = connection.getResponseCode();
            logger.info("BioPortal http response: " + responseCode);

            if (responseCode == 400 || responseCode == 403) {
                throw new BioPortalAccessDeniedException();
            }

            JsonParser parser = new JsonFactory().createParser(connection.getInputStream());
            while (format == null && parser.nextToken() != null) {
                String name = parser.getCurrentName();
                if ("hasOntologyLanguage".equals(name)) {
                    parser.nextToken();
                    format = parser.getText();
                }
            }
            if (format == null) {
                format = "unknown";
            }
            cache.storeFormat(ontologyAcronym, format);
        } catch (UnknownHostException e) {
            ErrorHandler.getErrorHandler().handleError(e);
        } catch (MalformedURLException e) {
            logger.error("Error with URL for BioPortal rest API", e);
        } catch (SocketTimeoutException e) {
            logger.error("Timeout connecting to BioPortal", e);
            ErrorHandler.getErrorHandler().handleError(e);
        } catch (IOException e) {
            logger.error("Error communiciating with BioPortal rest API", e);
        } catch (BioPortalAccessDeniedException e) {
            ErrorHandler.getErrorHandler().handleError(e);
        }
    }

    return format;
}

From source file:eu.codeplumbers.cosi.api.tasks.RegisterDeviceTask.java

@Override
protected Device doInBackground(Void... voids) {
    URL urlO = null;//from w w  w  . j av a2s . c o  m
    try {
        urlO = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        OutputStream os = conn.getOutputStream();
        os.write(deviceString.getBytes("UTF-8"));
        os.flush();

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONObject jsonObject = new JSONObject(result);

        if (jsonObject != null) {
            if (jsonObject.has("login")) {
                resultDevice = new Device();
                resultDevice.setUrl(url.replace("/device/", ""));
                //Log.d(getClass().getName(), "Token="+jsonObject.getString("login"));
                resultDevice.setLogin(jsonObject.getString("login"));
                resultDevice.setPassword(jsonObject.getString("password"));
                resultDevice.setPermissions(jsonObject.getString("permissions"));

                resultDevice.setFirstSyncDone(false);
                resultDevice.setSyncCalls(false);
                resultDevice.setSyncContacts(false);
                resultDevice.setSyncFiles(false);
                resultDevice.setSyncNotes(false);

                resultDevice.save();
            } else {
                errorMessage = jsonObject.getString("error");
            }
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        errorMessage = e.getLocalizedMessage();
    } catch (ProtocolException e) {
        errorMessage = e.getLocalizedMessage();
    } catch (IOException e) {
        errorMessage = e.getLocalizedMessage();
    } catch (JSONException e) {
        errorMessage = e.getLocalizedMessage();
    }

    return resultDevice;
}

From source file:eu.codeplumbers.cosi.api.tasks.DeleteFileTask.java

private String deleteFileRequest(File file) {
    String result = "";
    URL urlO = null;/*  w  ww.  jav a  2  s  .co m*/
    try {
        urlO = new URL(url + file.getRemoteId() + "/");
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoOutput(false);
        conn.setDoInput(true);

        conn.setRequestMethod("DELETE");

        // read the response
        InputStream in = new BufferedInputStream(conn.getInputStream());

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        result = writer.toString();

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        result = e.getLocalizedMessage();
    } catch (ProtocolException e) {
        result = e.getLocalizedMessage();
        e.printStackTrace();
    } catch (IOException e) {
        result = e.getLocalizedMessage();
    }

    return result;
}

From source file:com.ardnezar.lookapp.RoomParametersFetcher.java

private LinkedList<PeerConnection.IceServer> requestTurnServers(String url) throws IOException, JSONException {
    LinkedList<PeerConnection.IceServer> turnServers = new LinkedList<PeerConnection.IceServer>();
    Log.d(TAG, "Request TURN from: " + url);
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setConnectTimeout(TURN_HTTP_TIMEOUT_MS);
    connection.setReadTimeout(TURN_HTTP_TIMEOUT_MS);
    int responseCode = connection.getResponseCode();
    if (responseCode != 200) {
        throw new IOException("Non-200 response when requesting TURN server from " + url + " : "
                + connection.getHeaderField(null));
    }//from ww w .  j av  a 2 s.  co  m
    InputStream responseStream = connection.getInputStream();
    String response = drainStream(responseStream);
    connection.disconnect();
    Log.d(TAG, "TURN response: " + response);
    JSONObject responseJSON = new JSONObject(response);
    String username = responseJSON.getString("username");
    String password = responseJSON.getString("password");
    JSONArray turnUris = responseJSON.getJSONArray("uris");
    for (int i = 0; i < turnUris.length(); i++) {
        String uri = turnUris.getString(i);
        turnServers.add(new PeerConnection.IceServer(uri, username, password));
    }
    return turnServers;
}

From source file:com.juick.android.Utils.java

public static RESTResponse postForm(final Context context, final String url, ArrayList<NameValuePair> data) {
    try {//from w  w w.j  av  a  2  s .  c  om
        final String end = "\r\n";
        final String twoHyphens = "--";
        final String boundary = "****+++++******+++++++********";

        URL apiUrl = new URL(url);

        final HttpURLConnection conn = (HttpURLConnection) apiUrl.openConnection();
        conn.setConnectTimeout(10000);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        conn.connect();
        OutputStream out = conn.getOutputStream();

        PrintStream ps = new PrintStream(out);
        int index = 0;
        byte[] block = new byte[1024];
        for (NameValuePair nameValuePair : data) {
            ps.print(twoHyphens + boundary + end);
            ps.print("Content-Disposition: form-data; name=\"" + nameValuePair.getName() + "\"" + end + end);
            final InputStream value = nameValuePair.getValue();
            while (true) {
                final int rd = value.read(block, 0, block.length);
                if (rd < 1) {
                    break;
                }
                ps.write(block, 0, rd);
            }
            value.close();
            ps.print(end);
        }
        ps.print(twoHyphens + boundary + twoHyphens + end);
        ps.close();
        boolean b = conn.getResponseCode() == 200;
        if (!b) {
            return new RESTResponse("HTTP " + conn.getResponseCode() + ": " + conn.getResponseMessage(), false,
                    null);
        } else {
            InputStream inputStream = conn.getInputStream();
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] arr = new byte[1024];
                while (true) {
                    int rd = inputStream.read(arr);
                    if (rd < 1)
                        break;
                    baos.write(arr, 0, rd);
                }
                if (conn.getHeaderField("X-GZIPCompress") != null) {
                    return new RESTResponse(null, false, baos.toString(0));
                } else {
                    return new RESTResponse(null, false, baos.toString());
                }
            } finally {
                inputStream.close();
            }
        }
    } catch (IOException e) {
        return new RESTResponse(e.toString(), false, null);
    }
}

From source file:com.mercandalli.android.apps.files.common.net.TaskGet.java

@Override
protected String doInBackground(Void... urls) {
    try {//from ww w  .  j a v  a2  s  . co m
        if (this.parameters != null) {
            if (!StringUtils.isNullOrEmpty(Config.getNotificationId())) {
                parameters.add(new StringPair("android_id", "" + Config.getNotificationId()));
            }
            url = NetUtils.addUrlParameters(url, parameters);
        }

        Log.d("TaskGet", "url = " + url);

        URL tmp_url = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) tmp_url.openConnection();
        conn.setReadTimeout(10_000);
        conn.setConnectTimeout(15_000);
        conn.setRequestMethod("GET");
        if (isAuthentication) {
            conn.setRequestProperty("Authorization", "Basic " + Config.getUserToken());
        }
        conn.setUseCaches(false);
        conn.setDoInput(true);

        conn.connect(); // Starts the query
        int responseCode = conn.getResponseCode();
        InputStream inputStream = new BufferedInputStream(conn.getInputStream());

        // convert inputstream to string
        String resultString = convertInputStreamToString(inputStream);

        //int responseCode = response.getStatusLine().getStatusCode();
        if (responseCode >= 300) {
            resultString = "Status Code " + responseCode + ". " + resultString;
        }

        conn.disconnect();

        return resultString;
    } catch (IOException e) {
        Log.e(getClass().getName(), "IOException", e);
    }
    return null;
}

From source file:org.mf.api.net.stack.HurlStack.java

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

    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setChunkedStreamingMode(0);

    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
    }

    return connection;
}

From source file:corner.payment.services.impl.processor.AlipayProcessor.java

@Override
public boolean verifyNotify(String notifyId) {
    if (notifyId == null) {
        throw new IllegalArgumentException("The notifyId is null");
    }/*w w  w.  j  ava  2s.c  o m*/
    String alipayNotifyURL = String.format("%s?partner=%s&notify_id=%s", QUERY_URL, partner, notifyId);
    java.io.Closeable input = null;
    try {
        URL url = new URL(alipayNotifyURL);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoOutput(false);
        urlConnection.setConnectTimeout(30 * 1000);
        urlConnection.setReadTimeout(30 * 1000);
        BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        input = in;
        String inputLine = in.readLine().toString();
        urlConnection.disconnect();
        if ("true".equalsIgnoreCase(inputLine)) {
            return true;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
            }
        }
    }
    return false;
}

From source file:com.graphhopper.http.NominatimGeocoder.java

HttpURLConnection openConnection(String url) throws IOException {
    HttpURLConnection hConn = (HttpURLConnection) new URL(url).openConnection();
    ;/*from   w w w  .j  av  a  2s  .  co m*/
    hConn.setRequestProperty("User-Agent", userAgent);
    hConn.setRequestProperty("content-charset", "UTF-8");
    hConn.setConnectTimeout(timeoutInMillis);
    hConn.setReadTimeout(timeoutInMillis);
    hConn.connect();
    return hConn;
}

From source file:com.dell.asm.asmcore.asmmanager.util.discovery.DeviceTypeCheckUtil.java

public static int httpGet(String urlToRead) throws IOException {
    URL url;//from ww  w.  j  a  v  a 2  s .co m
    HttpURLConnection conn;
    BufferedReader rd = null;
    StringBuffer result = new StringBuffer();
    int responseCode = 400;

    try {
        url = new URL(urlToRead);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(10);
        responseCode = conn.getResponseCode();

    } catch (RuntimeException e) {
        throw new IOException("Could not connect to the url: " + e.getMessage());
    } catch (Exception e) {
        throw new IOException("Could not connect to the url: " + urlToRead);
    } finally {
        if (rd != null)
            rd.close();
    }
    return responseCode;
}