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.shopgun.android.sdk.network.impl.HttpURLNetwork.java

private HttpURLConnection openConnection(Request<?> request, URL url) throws IOException {

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    connection.setConnectTimeout(request.getTimeOut());
    connection.setReadTimeout(request.getTimeOut());
    connection.setUseCaches(false);//  w ww  . j a va2s  . c o m
    connection.setDoInput(true);
    connection.setInstanceFollowRedirects(false);

    setHeaders(request, connection);
    setRequestMethod(connection, request);
    return connection;
}

From source file:com.anyonavinfo.commonuserregister.MainActivity.java

/**
 * Post?//from w  w  w . ja  v a2 s  .c om
 */
public static String doPost(String urlStr, File file) {
    URL url = null;
    HttpURLConnection conn = null;
    InputStream is = null;
    ByteArrayOutputStream baos = null;
    String BOUNDARY = UUID.randomUUID().toString(); //  ??
    String PREFIX = "--", LINE_END = "\r\n";
    String CONTENT_TYPE = "multipart/form-data"; // 

    try {
        url = new URL(urlStr);
        conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true); // ??
        conn.setDoOutput(true); // ??
        conn.setUseCaches(false); // ??
        conn.setRequestProperty("encoding", "utf-8");
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

        if (file != null) {
            /**
             * ?
             */
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            StringBuffer sb = new StringBuffer();
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINE_END);
            /**
             * ?? name???key ?key ??
             * filename??????
             */

            sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\""
                    + LINE_END);
            sb.append("Content-Type: application/octet-stream; charset=" + "utf-8" + LINE_END);
            sb.append(LINE_END);
            dos.write(sb.toString().getBytes());
            InputStream IS = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = IS.read(bytes)) != -1) {
                dos.write(bytes, 0, len);
            }
            IS.close();
            dos.write(LINE_END.getBytes());
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
            dos.write(end_data);
            dos.flush();
        }

        if (conn.getResponseCode() == 200) {
            is = conn.getInputStream();
            baos = new ByteArrayOutputStream();
            int len = -1;
            byte[] buf = new byte[128];

            while ((len = is.read(buf)) != -1) {
                baos.write(buf, 0, len);
                Log.d("Sjj--->", len + "");
            }
            baos.flush();
            return baos.toString();
        } else {
            throw new RuntimeException(" responseCode is not 200 ... ");
        }

    } catch (Exception e) {
        // 
        if (e instanceof SocketTimeoutException) {
            return "SocketTimeoutException";
        } else if (e instanceof UnknownHostException) {
            return "UnknownHostException";
        }
        e.printStackTrace();
    } finally {
        try {
            if (is != null)
                is.close();
            if (baos != null)
                baos.close();
            if (conn != null) {
                conn.disconnect();
            }
        } catch (IOException e) {
        }
    }

    return null;
}

From source file:uk.ac.manchester.cs.owl.semspreadsheets.repository.bioportal.BioPortalRepositoryAccessor.java

public Collection<RepositoryItem> getOntologies() {
    final Collection<RepositoryItem> items = new ArrayList<RepositoryItem>();
    URL url = null;//www  .ja va 2 s.c o  m
    try {

        url = new URL(
                BioPortalRepository.ONTOLOGY_LIST + "?format=json&apikey=" + BioPortalRepository.readAPIKey());

        logger.debug("Contacting BioPortal REST API at: " + 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();
        }
        ObjectMapper mapper = new ObjectMapper();

        JsonNode node = mapper.readTree(connection.getInputStream());
        for (final JsonNode item : node) {
            String name = item.get("name").asText();
            String id = item.get("acronym").asText();

            BioPortalRepositoryItem repositoryItem = new BioPortalRepositoryItem(id, name, this);
            if (repositoryItem.isCompatible()) {
                items.add(repositoryItem);
            }
        }
        if (SAVE_PROPERTIES_CACHE) {
            BioPortalCache.getInstance().dumpStoredProperties();
        }
    } 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 items;
}

From source file:com.google.android.apps.santatracker.service.RemoteApiProcessor.java

/**
 * Downloads the given URL and return//  w w  w.  ja  v a  2s  .c  o m
 */
protected String downloadUrl(String myurl) throws IOException {
    InputStream is = null;
    // Only display the first 500 characters of the retrieved
    // web page content.
    // int len = 500;

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        if (!isValidHeader(conn)) {
            // not a valid header
            Log.d(TAG, "Santa communication failure.");
            return null;

        } else if (response != 200) {
            Log.d(TAG, "Santa communication failure " + response);
            return null;

        } else {
            is = conn.getInputStream();

            // Convert the InputStream into a string
            return read(is).toString();
        }

        // Makes sure that the InputStream is closed
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:com.eryansky.common.web.servlet.RemoteContentServlet.java

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

    HttpURLConnection connection = (HttpURLConnection) new URL(contentUrl).openConnection();
    // Socket//w  ww.  j a v a2  s.c  om
    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: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  www  . j a va 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:com.mabi87.httprequestbuilder.HTTPRequest.java

/**
 * @throws IOException//from w w w. j a v  a 2  s .c o  m
 *             throws from HttpURLConnection method.
 * @return the HTTPResponse object
 */
private HTTPResponse get() throws IOException {
    URL url = null;

    if (mParameters.size() > 0) {
        url = new URL(mPath + "?" + getQuery(mParameters));
    } else {
        url = new URL(mPath);
    }

    HttpURLConnection lConnection = (HttpURLConnection) url.openConnection();

    lConnection.setReadTimeout(mReadTimeoutMillis);
    lConnection.setConnectTimeout(mConnectTimeoutMillis);
    lConnection.setRequestMethod("GET");
    lConnection.setDoInput(true);

    HTTPResponse response = readPage(lConnection);

    return response;
}

From source file:com.mabi87.httprequestbuilder.HTTPRequest.java

/**
 * @throws IOException//w  w  w  .  j a  v a 2s .c  o  m
 *             throws from HttpURLConnection method.
 * @return the HTTPResponse object
 */
private HTTPResponse post() throws IOException {
    URL url = new URL(mPath);
    HttpURLConnection lConnection = (HttpURLConnection) url.openConnection();

    lConnection.setReadTimeout(mReadTimeoutMillis);
    lConnection.setConnectTimeout(mConnectTimeoutMillis);
    lConnection.setRequestMethod("POST");
    lConnection.setDoInput(true);
    lConnection.setDoOutput(true);

    OutputStream lOutStream = lConnection.getOutputStream();
    BufferedWriter lWriter = new BufferedWriter(new OutputStreamWriter(lOutStream, "UTF-8"));
    lWriter.write(getQuery(mParameters));
    lWriter.flush();
    lWriter.close();
    lOutStream.close();

    HTTPResponse response = readPage(lConnection);

    return response;
}

From source file:com.joyent.manta.client.MantaClientSigningIT.java

@Test
public final void testCanCreateSignedPUTUriFromPath() throws IOException, InterruptedException {
    if (config.isClientEncryptionEnabled()) {
        throw new SkipException("Signed URLs are not decrypted by the client");
    }// w ww .j  av a  2 s  .  c  o m

    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;

    Instant expires = Instant.now().plus(1, ChronoUnit.HOURS);
    URI uri = mantaClient.getAsSignedURI(path, "PUT", expires);

    HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();

    connection.setReadTimeout(3000);
    connection.setRequestMethod("PUT");
    connection.setDoOutput(true);
    connection.setChunkedStreamingMode(10);
    connection.connect();

    try (OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), UTF_8)) {
        out.write(TEST_DATA);
    } finally {
        connection.disconnect();
    }

    // Wait for file to become available
    for (int i = 0; i < 10; i++) {
        Thread.sleep(500);

        if (mantaClient.existsAndIsAccessible(path)) {
            break;
        }
    }

    String actual = mantaClient.getAsString(path);
    Assert.assertEquals(actual, TEST_DATA);
}

From source file:com.breadwallet.tools.util.JsonParser.java

private static String callURL(String myURL) {
    //        System.out.println("Requested URL_EA:" + myURL);
    StringBuilder sb = new StringBuilder();
    HttpURLConnection urlConn = null;
    InputStreamReader in = null;//from  w w w  .ja  v a2s . c o m
    try {
        URL url = new URL(myURL);
        urlConn = (HttpURLConnection) url.openConnection();
        int versionNumber = 0;
        MainActivity app = MainActivity.app;
        if (app != null) {
            try {
                PackageInfo pInfo = null;
                pInfo = app.getPackageManager().getPackageInfo(app.getPackageName(), 0);
                versionNumber = pInfo.versionCode;
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }
        int stringId = 0;
        String appName = "";
        if (app != null) {
            stringId = app.getApplicationInfo().labelRes;
            appName = app.getString(stringId);
        }
        String message = String.format(Locale.getDefault(), "%s/%d/%s",
                appName.isEmpty() ? "breadwallet" : appName, versionNumber, System.getProperty("http.agent"));
        urlConn.setRequestProperty("User-agent", message);
        urlConn.setReadTimeout(60 * 1000);

        String strDate = urlConn.getHeaderField("date");

        if (strDate == null || app == null) {
            Log.e(TAG, "callURL: strDate == null!!!");
        } else {
            @SuppressWarnings("deprecation")
            long date = Date.parse(strDate) / 1000;
            SharedPreferencesManager.putSecureTime(app, date);
            Assert.assertTrue(date != 0);
        }

        if (urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());
            BufferedReader bufferedReader = new BufferedReader(in);

            int cp;
            while ((cp = bufferedReader.read()) != -1) {
                sb.append((char) cp);
            }
            bufferedReader.close();
        }
        assert in != null;
        in.close();
    } catch (Exception e) {
        return null;
    }

    return sb.toString();
}