List of usage examples for java.net HttpURLConnection setReadTimeout
public void setReadTimeout(int timeout)
From source file:com.baasbox.android.HttpUrlConnectionClient.java
private HttpURLConnection openConnection(String urlString) throws BaasIOException, IOException { URL url = null;//from w w w . j a v a 2 s . c om try { url = new URL(urlString); } catch (MalformedURLException e) { throw new BaasIOException("Error while parsing url " + urlString, e); } HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(config.httpConnectionTimeout); connection.setReadTimeout(config.httpSocketTimeout); connection.setInstanceFollowRedirects(true); connection.setDoInput(true); return connection; }
From source file:info.icefilms.icestream.browse.Location.java
protected static String DownloadPage(URL url, String sendCookie, String sendData, StringBuilder getCookie, Callback callback) {//from w w w . ja v a2 s . c om // Declare our buffer ByteArrayBuffer byteArrayBuffer; try { // Setup the connection HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux i686; rv:2.0) Gecko/20100101 Firefox/4.0"); urlConnection.setRequestProperty("Referer", mIceFilmsURL.toString()); if (sendCookie != null) urlConnection.setRequestProperty("Cookie", sendCookie); if (sendData != null) { urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlConnection.setDoOutput(true); } urlConnection.setConnectTimeout(callback.GetConnectionTimeout()); urlConnection.setReadTimeout(callback.GetConnectionTimeout()); urlConnection.connect(); // Get the output stream and send the data if (sendData != null) { OutputStream outputStream = urlConnection.getOutputStream(); outputStream.write(sendData.getBytes()); outputStream.flush(); outputStream.close(); } // Get the cookie if (getCookie != null) { // Clear the string builder getCookie.delete(0, getCookie.length()); // Loop thru the header fields String headerName; String cookie; for (int i = 1; (headerName = urlConnection.getHeaderFieldKey(i)) != null; ++i) { if (headerName.equalsIgnoreCase("Set-Cookie")) { // Get the cookie cookie = GetGroup("([^=]+=[^=;]+)", urlConnection.getHeaderField(i)); // Add it to the string builder if (cookie != null) getCookie.append(cookie); break; } } } // Get the input stream InputStream inputStream = urlConnection.getInputStream(); // For some reason we can actually get a null InputStream instead of an exception if (inputStream == null) { Log.e("Ice Stream", "Page download failed. Unable to create Input Stream."); if (callback.GetErrorBoolean() == false) { callback.SetErrorBoolean(true); callback.SetErrorStringID(R.string.browse_page_download_error); } urlConnection.disconnect(); return null; } // Get the file size final int fileSize = urlConnection.getContentLength(); // Create our buffers byte[] byteBuffer = new byte[2048]; byteArrayBuffer = new ByteArrayBuffer(2048); // Download the page int amountDownloaded = 0; int count; while ((count = inputStream.read(byteBuffer, 0, 2048)) != -1) { // Check if we got canceled if (callback.IsCancelled()) { inputStream.close(); urlConnection.disconnect(); return null; } // Add data to the buffer byteArrayBuffer.append(byteBuffer, 0, count); // Update the downloaded amount amountDownloaded += count; } // Close the connection inputStream.close(); urlConnection.disconnect(); // Check for amount downloaded calculation error if (fileSize != -1 && amountDownloaded != fileSize) { Log.w("Ice Stream", "Total amount downloaded (" + amountDownloaded + " bytes) does not " + "match reported content length (" + fileSize + " bytes)."); } } catch (SocketTimeoutException exception) { Log.e("Ice Stream", "Page download failed.", exception); if (callback.GetErrorBoolean() == false) { callback.SetErrorBoolean(true); callback.SetErrorStringID(R.string.browse_page_timeout_error); } return null; } catch (IOException exception) { Log.e("Ice Stream", "Page download failed.", exception); if (callback.GetErrorBoolean() == false) { callback.SetErrorBoolean(true); callback.SetErrorStringID(R.string.browse_page_download_error); } return null; } // Convert things to a string return new String(byteArrayBuffer.toByteArray()); }
From source file:com.zlk.bigdemo.android.volley.toolbox.HurlStack.java
/** * Opens an {@link HttpURLConnection} with parameters. * @param url/* w w w .j a v a 2s .c om*/ * @return an open connection * @throws IOException */ 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); // use caller-provided custom SslSocketFactory, if any, for HTTPS if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory); } return connection; }
From source file:com.joyent.manta.client.MantaClientSigningIT.java
@Test public final void testCanCreateSignedGETUriFromPath() throws IOException { if (config.isClientEncryptionEnabled()) { throw new SkipException("Signed URLs are not decrypted by the client"); }/* www. ja v a2 s . c o m*/ final String name = UUID.randomUUID().toString(); final String path = testPathPrefix + name; mantaClient.put(path, TEST_DATA); // This will throw an error if the newly inserted object isn't present mantaClient.head(path); Instant expires = Instant.now().plus(1, ChronoUnit.HOURS); URI uri = mantaClient.getAsSignedURI(path, "GET", expires); HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection(); try (InputStream is = connection.getInputStream()) { connection.setReadTimeout(3000); connection.connect(); if (connection.getResponseCode() != 200) { Assert.fail(IOUtils.toString(connection.getErrorStream(), Charset.defaultCharset())); } String actual = IOUtils.toString(is, Charset.defaultCharset()); Assert.assertEquals(actual, TEST_DATA); } finally { connection.disconnect(); } }
From source file:com.streamsets.datacollector.updatechecker.UpdateChecker.java
@Override public void run() { updateInfo = null;/*from w w w . j a v a 2 s . c o m*/ PipelineState ps; try { ps = runner.getState(); } catch (PipelineStoreException e) { LOG.warn(Utils.format("Cannot get pipeline state: '{}'", e.toString()), e); return; } if (ps.getStatus() == PipelineStatus.RUNNING) { if (url != null) { Map uploadInfo = getUploadInfo(); if (uploadInfo != null) { HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(2000); conn.setReadTimeout(2000); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("content-type", APPLICATION_JSON_MIME); ObjectMapperFactory.getOneLine().writeValue(conn.getOutputStream(), uploadInfo); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { String responseContentType = conn.getHeaderField("content-type"); if (APPLICATION_JSON_MIME.equals(responseContentType)) { updateInfo = ObjectMapperFactory.get().readValue(conn.getInputStream(), Map.class); } else { LOG.trace("Got invalid content-type '{}' from from update-check server", responseContentType); } } else { LOG.trace("Got '{} : {}' from update-check server", conn.getResponseCode(), conn.getResponseMessage()); } } catch (Exception ex) { LOG.trace("Could not do an update check: {}", ex.toString(), ex); } finally { if (conn != null) { conn.disconnect(); } } } } } }
From source file:com.atinternet.tracker.TVTrackingPlugin.java
@Override protected void execute(Tracker tracker) { this.tracker = tracker; try {//from w ww . j ava 2 s .c om if (sessionIsExpired()) { setDirectCampaignToRemanent(); URL url = new URL(tracker.TVTracking().getCampaignURL()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(TIMEOUT); connection.setConnectTimeout(TIMEOUT); connection.setDoInput(true); connection.connect(); response = getTvTrackingResponse(stringifyTvTResponse(connection), connection); connection.disconnect(); } else { response = getTvTrackingResponse( Tracker.getPreferences().getString(TrackerConfigurationKeys.DIRECT_CAMPAIGN_SAVED, null), null); } Tool.executeCallback(tracker.getListener(), Tool.CallbackType.partner, "TV Tracking : " + response); Tracker.getPreferences().edit() .putLong(TrackerConfigurationKeys.LAST_TVT_EXECUTE_TIME, System.currentTimeMillis()).apply(); } catch (Exception e) { e.printStackTrace(); } }
From source file:mSearch.filmlisten.FilmlisteLesen.java
private InputStream getInputStreamForLocation(String source) throws IOException, URISyntaxException { InputStream in;//from w ww .j a va 2 s .c om long size = 0; final URI uri; if (source.startsWith("http")) { uri = new URI(source); //remote address for internet download HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection(); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); conn.setRequestProperty("User-Agent", Config.getUserAgent()); if (conn.getResponseCode() < 400) { size = conn.getContentLengthLong(); } in = new ProgressMonitorInputStream(conn.getInputStream(), size, new InputStreamProgressMonitor() { private int oldProgress = 0; @Override public void progress(long bytesRead, long size) { final int iProgress = (int) (bytesRead * 100 / size); if (iProgress != oldProgress) { oldProgress = iProgress; notifyProgress(uri.toASCIIString(), "Download", iProgress); } } }); } else { //local file notifyProgress(source, "Download", PROGRESS_MAX); in = new FileInputStream(source); } return in; }
From source file:org.openintents.openpgp.keyserver.HkpKeyServer.java
private String submitQuery(String request) throws QueryException, HttpError { InetAddress ips[];// w w w .jav a 2s.co m try { ips = InetAddress.getAllByName(mHost); } catch (UnknownHostException e) { throw new QueryException(e.toString()); } for (int i = 0; i < ips.length; ++i) { try { String url = "http://" + ips[i].getHostAddress() + ":" + mPort + request; URL realUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(25000); conn.connect(); int response = conn.getResponseCode(); if (response >= 200 && response < 300) { return readAll(conn.getInputStream(), conn.getContentEncoding()); } else { String data = readAll(conn.getErrorStream(), conn.getContentEncoding()); throw new HttpError(response, data); } } catch (MalformedURLException e) { // nothing to do, try next IP } catch (IOException e) { // nothing to do, try next IP } } throw new QueryException("querying server(s) for '" + mHost + "' failed"); }
From source file:com.android.volley.toolbox.HurlStack.java
/** * Opens an {@link HttpURLConnection} with parameters. * @param url//from w w w.ja va 2s .co m * @return an open connection * @throws IOException */ 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); // 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:com.mercandalli.android.apps.files.common.net.TaskPost.java
@Override protected String doInBackground(Void... urls) { try {/* w w w. j ava 2 s . c o m*/ if (this.mParameters != null) { if (!StringUtils.isNullOrEmpty(Config.getNotificationId())) { mParameters.add(new StringPair("android_id", "" + Config.getNotificationId())); } url = NetUtils.addUrlParameters(url, mParameters); } Log.d("TaskGet", "url = " + url); final URL tmpUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) tmpUrl.openConnection(); conn.setReadTimeout(10_000); conn.setConnectTimeout(15_000); conn.setRequestMethod("POST"); conn.setRequestProperty("Authorization", "Basic " + Config.getUserToken()); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); if (this.mParameters != null) { final OutputStream outputStream = conn.getOutputStream(); final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); writer.write(getQuery(mParameters)); writer.flush(); writer.close(); outputStream.close(); } 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(), "Failed to convert Json", e); } return null; // try { // // // http://stackoverflow.com/questions/9767952/how-to-add-parameters-to-httpurlconnection-using-post // // HttpPost httppost = new HttpPost(url); // // MultipartEntity mpEntity = new MultipartEntity(); // if (this.file != null) mpEntity.addPart("file", new FileBody(file, "*/*")); // // String log_parameters = ""; // if (this.parameters != null) // for (StringPair b : parameters) { // mpEntity.addPart(b.getName(), new StringBody(b.getValue(), Charset.forName("UTF-8"))); // log_parameters += b.getName() + ":" + b.getValue() + " "; // } // Log.d("TaskPost", "url = " + url + " " + log_parameters); // // httppost.setEntity(mpEntity); // // StringBuilder authentication = new StringBuilder().append(app.getConfig().getUser().getAccessLogin()).append(":").append(app.getConfig().getUser().getAccessPassword()); // String result = Base64.encodeBytes(authentication.toString().getBytes()); // httppost.setHeader("Authorization", "Basic " + result); // // HttpClient httpclient = new DefaultHttpClient(); // HttpResponse response = httpclient.execute(httppost); // // // receive response as inputStream // InputStream inputStream = response.getEntity().getContent(); // // String resultString = null; // // // convert inputstream to string // if (inputStream != null) // resultString = convertInputStreamToString(inputStream); // // int responseCode = response.getStatusLine().getStatusCode(); // if (responseCode >= 300) // resultString = "Status Code " + responseCode + ". " + resultString; // return resultString; // // // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } catch (ClientProtocolException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // return null; }