List of usage examples for java.net HttpURLConnection setReadTimeout
public void setReadTimeout(int timeout)
From source file:com.centurylink.mdw.util.HttpHelper.java
/** * Configures the connection timeout values and headers. *//*from w ww . j a v a2 s. com*/ protected void prepareConnection(HttpURLConnection connection) throws IOException { if (readTimeout >= 0) connection.setReadTimeout(readTimeout); if (connectTimeout >= 0) connection.setConnectTimeout(connectTimeout); if (headers != null) { for (String key : headers.keySet()) { connection.setRequestProperty(key, headers.get(key)); } } if (user != null) { String value = user + ":" + password; connection.setRequestProperty(HTTP_BASIC_AUTH_HEADER, "Basic " + new String(Base64.encodeBase64(value.getBytes()))); } }
From source file:com.owly.srv.RemoteBasicStatItfImpl.java
public boolean getStatusRemoteServer(String ipSrv, int clientPort) { URL url = null;/*from w ww. jav a 2 s .c o m*/ BufferedReader reader = null; StringBuilder stringBuilder; JSONObject objJSON = new JSONObject(); JSONParser objParser = new JSONParser(); String statusServer = "Enable"; // Check status of remote server with healthCheck logger.debug("Check status of remote server with healthCheck"); // Url to send to remote server // for example : // http://135.1.128.127:5000/healthCheck String urlToSend = "http://" + ipSrv + ":" + clientPort + "/healthCheck"; logger.debug("URL for HTTP request : " + urlToSend); HttpURLConnection connection; try { url = new URL(urlToSend); connection = (HttpURLConnection) url.openConnection(); // just want to do an HTTP GET here connection.setRequestMethod("GET"); // uncomment this if you want to write output to this url // connection.setDoOutput(true); // give it 2 second to respond connection.setReadTimeout(1 * 1000); connection.connect(); // read the output from the server reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); stringBuilder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { stringBuilder.append(line + "\n"); } logger.debug("Response received : " + stringBuilder.toString()); // map the response into a JSON object objJSON = (JSONObject) objParser.parse(stringBuilder.toString()); // Check the response of the sever with the previous request String resServer = (String) objJSON.get("StatusServer"); // If we dont receive the correct health checl we will save the // disable state in the database if (resServer.equals("OK")) { statusServer = "Enable"; } else { statusServer = "Disable"; } logger.debug("Status of the Server: " + statusServer); } catch (MalformedURLException e1) { logger.error("MalformedURLException : " + e1.getMessage()); logger.error("Exception ::", e1); statusServer = "Disable"; logger.debug("Status of the Server: " + statusServer); } catch (IOException e1) { logger.error("IOException : " + e1.toString()); logger.error("Exception ::", e1); e1.printStackTrace(); statusServer = "Disable"; logger.debug("Status of the Server: " + statusServer); } catch (ParseException e1) { logger.error("ParseException : " + e1.toString()); logger.error("Exception ::", e1); statusServer = "Disable"; logger.debug("Status of the Server: " + statusServer); } finally { logger.debug("Save Status of Server in Database: " + statusServer); } if (statusServer.equals("Enable")) { return true; } else { return false; } }
From source file:com.mobiperf_library.measurements.PingTask.java
/** * Use the HTTP Head method to emulate ping. The measurement from this method can be * substantially (2x) greater than the first two methods and inaccurate. This is because, * depending on the implementing of the destination web server, either a quick HTTP * response is replied or some actual heavy lifting will be done in preparing the response * *///from w w w. j a va 2s. c o m private MeasurementResult executeHttpPingTask() throws MeasurementError { long pingStartTime = 0; long pingEndTime = 0; ArrayList<Double> rrts = new ArrayList<Double>(); PingDesc pingTask = (PingDesc) this.measurementDesc; String errorMsg = ""; MeasurementResult result = null; try { long totalPingDelay = 0; URL url = new URL("http://" + pingTask.target); int timeOut = (int) (3000 * (double) pingTask.pingTimeoutSec / Config.PING_COUNT_PER_MEASUREMENT); for (int i = 0; i < Config.PING_COUNT_PER_MEASUREMENT; i++) { pingStartTime = System.currentTimeMillis(); HttpURLConnection httpClient = (HttpURLConnection) url.openConnection(); httpClient.setRequestProperty("Connection", "close"); httpClient.setRequestMethod("HEAD"); httpClient.setReadTimeout(timeOut); httpClient.setConnectTimeout(timeOut); httpClient.connect(); pingEndTime = System.currentTimeMillis(); httpClient.disconnect(); rrts.add((double) (pingEndTime - pingStartTime)); this.progress = 100 * i / Config.PING_COUNT_PER_MEASUREMENT; broadcastProgressForUser(progress); } Logger.i("HTTP get ping succeeds"); Logger.i("RTT is " + rrts.toString()); double packetLoss = 1 - ((double) rrts.size() / (double) Config.PING_COUNT_PER_MEASUREMENT); result = constructResult(rrts, packetLoss, Config.PING_COUNT_PER_MEASUREMENT, PING_METHOD_HTTP); } catch (MalformedURLException e) { Logger.e(e.getMessage()); errorMsg += e.getMessage() + "\n"; } catch (IOException e) { Logger.e(e.getMessage()); errorMsg += e.getMessage() + "\n"; } if (result != null) { return result; } else { Logger.i("HTTP get ping fails"); throw new MeasurementError(errorMsg); } }
From source file:com.vibeosys.utils.dbdownloadv1.DbDownload.java
public String downloadDatabase() { boolean flag = false; HttpURLConnection urlConnection = null; OutputStream myOutput = null; byte[] buffer = null; InputStream inputStream = null; String message = FAIL;// w w w . java 2 s.c o m System.out.print(downloadDBURL); try { URL url = new URL(downloadDBURL); urlConnection = (HttpURLConnection) url.openConnection(); System.out.println("##Request Sent..."); urlConnection.setDoOutput(true); urlConnection.setUseCaches(false); urlConnection.setConnectTimeout(20000); urlConnection.setReadTimeout(10000); urlConnection.connect(); int Http_Result = urlConnection.getResponseCode(); String res = urlConnection.getResponseMessage(); System.out.println(res); System.out.println(String.valueOf(Http_Result)); if (Http_Result == HttpURLConnection.HTTP_OK) { String contentType = urlConnection.getContentType(); inputStream = urlConnection.getInputStream(); System.out.println(contentType); if (contentType.equals("application/octet-stream")) { buffer = new byte[1024]; myOutput = new FileOutputStream(this.dbFile); int length; while ((length = inputStream.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } myOutput.flush(); myOutput.close(); inputStream.close(); flag = true; message = SUCCESS; } else if (contentType.equals("application/json; charset=UTF-8")) { message = FAIL; flag = false; String responce = convertStreamToString(inputStream); System.out.println(responce); try { JSONObject jsResponce = new JSONObject(responce); message = jsResponce.getString("message"); } catch (JSONException e) { // addError(screenName, "Json error in downloadDatabase", e.getMessage()); System.out.println(e.toString()); } } } } catch (Exception ex) { System.out.println("##ROrder while downloading database" + ex.toString()); //addError(screenName, "downloadDatabase", ex.getMessage()); } return message; }
From source file:com.google.ytd.picasa.PicasaApiHelper.java
public PhotoEntry doResumableUpload(com.google.ytd.model.PhotoEntry photoEntry) throws IllegalArgumentException { if (util.isNullOrEmpty(photoEntry.getResumableUploadUrl())) { throw new IllegalArgumentException(String .format("No resumable upload URL found for " + "PhotoEntry id '%s'.", photoEntry.getId())); }/* w ww.j av a 2 s.c o m*/ try { URL url = new URL(photoEntry.getResumableUploadUrl()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(CONNECT_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); connection.setRequestMethod("PUT"); connection.setRequestProperty("Content-Range", "bytes */*"); // Response code 308 is specific to this use case and doesn't appear to have a // HttpURLConnection constant. if (connection.getResponseCode() == 308) { long previousByte = 0; String rangeHeader = connection.getHeaderField("Range"); if (!util.isNullOrEmpty(rangeHeader)) { LOG.info("Range header in 308 response is " + rangeHeader); String[] rangeHeaderSplits = rangeHeader.split("-", 2); if (rangeHeaderSplits.length == 2) { previousByte = Long.valueOf(rangeHeaderSplits[1]).longValue() + 1; } } connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setDoOutput(true); connection.setConnectTimeout(CONNECT_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); connection.setRequestMethod("PUT"); byte[] bytes; String contentRangeHeader; if (photoEntry.getBlobKey() != null) { long lastByte = previousByte + CHUNK_SIZE; if (lastByte > (photoEntry.getOriginalFileSize() - 1)) { lastByte = photoEntry.getOriginalFileSize() - 1; } contentRangeHeader = String.format("bytes %d-%d/%d", previousByte, lastByte, photoEntry.getOriginalFileSize()); BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService(); bytes = blobstoreService.fetchData(photoEntry.getBlobKey(), previousByte, lastByte); } else { bytes = dataChunkDao.getBytes(photoEntry.getId(), previousByte); if (bytes == null) { throw new IllegalArgumentException(String.format("PhotoEntry with id '%s' does not " + "have a valid blob key. Additionally, there is no DataChunk entry for the " + "initial byte '%d'.", photoEntry.getId(), previousByte)); } contentRangeHeader = String.format("bytes %d-%d/%d", previousByte, previousByte + bytes.length - 1, photoEntry.getOriginalFileSize()); } connection.setRequestProperty("Content-Length", String.valueOf(bytes.length)); LOG.info("Using the following for Content-Range header: " + contentRangeHeader); connection.setRequestProperty("Content-Range", contentRangeHeader); OutputStream outputStream = connection.getOutputStream(); outputStream.write(bytes); outputStream.close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) { LOG.info("Resumable upload is complete and successful."); return (PhotoEntry) ParseUtil.readEntry(new ParseSource(connection.getInputStream())); } } else if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) { // It's possible that the Picasa upload associated with the specific resumable upload URL // had previously completed successfully. In that case, the response to the initial */* PUT // will be a 201 Created with the new PhotoEntry. This is probably an edge case. LOG.info("Resumable upload is complete and successful."); return (PhotoEntry) ParseUtil.readEntry(new ParseSource(connection.getInputStream())); } else { // The IllegalArgumentException should be treated by the calling code as // something that is not recoverable, which is to say the resumable upload attempt // should be stopped. throw new IllegalArgumentException(String.format("HTTP POST to %s returned status %d (%s).", url.toString(), connection.getResponseCode(), connection.getResponseMessage())); } } catch (MalformedURLException e) { LOG.log(Level.WARNING, "", e); throw new IllegalArgumentException(e); } catch (IOException e) { LOG.log(Level.WARNING, "", e); } catch (ServiceException e) { LOG.log(Level.WARNING, "", e); } return null; }
From source file:count.ly.messaging.ConnectionProcessor.java
URLConnection urlConnectionForEventData(final String eventData) throws IOException { String urlStr = serverURL_ + "/i?"; if (!eventData.contains("&crash=")) urlStr += eventData;/* w ww. ja va2 s. co m*/ final URL url = new URL(urlStr); final HttpURLConnection conn; if (Countly.publicKeyPinCertificates == null) { conn = (HttpURLConnection) url.openConnection(); } else { HttpsURLConnection c = (HttpsURLConnection) url.openConnection(); c.setSSLSocketFactory(sslContext_.getSocketFactory()); conn = c; } conn.setConnectTimeout(CONNECT_TIMEOUT_IN_MILLISECONDS); conn.setReadTimeout(READ_TIMEOUT_IN_MILLISECONDS); conn.setUseCaches(false); conn.setDoInput(true); String picturePath = UserData.getPicturePathFromQuery(url); if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Got picturePath: " + picturePath); } if (!picturePath.equals("")) { //Uploading files: //http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests File binaryFile = new File(picturePath); conn.setDoOutput(true); // Just generate some unique random value. String boundary = Long.toHexString(System.currentTimeMillis()); // Line separator required by multipart/form-data. String CRLF = "\r\n"; String charset = "UTF-8"; conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); OutputStream output = conn.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true); // Send binary file. writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF); writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())) .append(CRLF); writer.append("Content-Transfer-Encoding: binary").append(CRLF); writer.append(CRLF).flush(); FileInputStream fileInputStream = new FileInputStream(binaryFile); byte[] buffer = new byte[1024]; int len; while ((len = fileInputStream.read(buffer)) != -1) { output.write(buffer, 0, len); } output.flush(); // Important before continuing with writer! writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary. fileInputStream.close(); // End of multipart/form-data. writer.append("--" + boundary + "--").append(CRLF).flush(); } else if (eventData.contains("&crash=")) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Using post because of crash"); } conn.setDoOutput(true); conn.setRequestMethod("POST"); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(eventData); writer.flush(); writer.close(); os.close(); } else { conn.setDoOutput(false); } return conn; }
From source file:io.apiman.gateway.platforms.servlet.connectors.HttpApiConnection.java
/** * If the endpoint properties includes a read timeout override, then * set it here./*from w w w . j a v a2s .co m*/ * @param connection */ private void setReadTimeout(HttpURLConnection connection) { try { Map<String, String> endpointProperties = this.api.getEndpointProperties(); if (endpointProperties.containsKey("timeouts.read")) { //$NON-NLS-1$ int connectTimeoutMs = new Integer(endpointProperties.get("timeouts.read")); //$NON-NLS-1$ connection.setReadTimeout(connectTimeoutMs); } } catch (Throwable t) { } }
From source file:com.embeddedlog.LightUpDroid.LightUpPiSync.java
/** * Initiates a background thread to check if the LightUpPi server is reachable. * * @param guiHandler Handler for the activity GUI, for which to send one of the two runnables. * @param online Runnable to execute in the Handler if the server is online. * @param offline Runnable to execute in the Handler if the server is offline. *///from w ww . j a v a2s.c om public void startBackgroundServerCheck(final Handler guiHandler, final Runnable online, final Runnable offline) { // Check for network connectivity ConnectivityManager connMgr = (ConnectivityManager) mActivityContext .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if ((networkInfo != null) && networkInfo.isConnected() && ((scheduleServerCheck == null) || scheduleServerCheck.isShutdown())) { // Get the ping address final Uri.Builder pingUri = getServerUriBuilder(); pingUri.appendPath("ping"); // Schedule the background server check scheduleServerCheck = Executors.newScheduledThreadPool(1); scheduleServerCheck.scheduleWithFixedDelay(new Runnable() { public void run() { int response = 0; try { URL url = new URL(pingUri.build().toString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(3000); /* milliseconds */ conn.setConnectTimeout(5000); /* milliseconds */ conn.setRequestMethod("GET"); conn.setDoInput(true); conn.connect(); response = conn.getResponseCode(); } catch (Exception e) { // Safely ignored as a response!=200 will trigger the offline title } if (response == 200) { if (Log.LOGV) Log.i(LOG_TAG + "Server response 200"); guiHandler.post(online); } else { if (Log.LOGV) Log.i(LOG_TAG + "Server response NOT 200"); guiHandler.post(offline); } } }, 0, 30, TimeUnit.SECONDS); if (Log.LOGV) Log.v(LOG_TAG + "BackgroundServerCheck started"); } else { if (Log.LOGV) Log.d(LOG_TAG + "Server response NOT 200"); guiHandler.post(offline); } }
From source file:com.mobiperf.measurements.PingTask.java
/** * Use the HTTP Head method to emulate ping. The measurement from this method can be * substantially (2x) greater than the first two methods and inaccurate. This is because, * depending on the implementing of the destination web server, either a quick HTTP * response is replied or some actual heavy lifting will be done in preparing the response * *//*from w w w .j a v a 2 s. c o m*/ private MeasurementResult executeHttpPingTask() throws MeasurementError { long pingStartTime = 0; long pingEndTime = 0; ArrayList<Double> rrts = new ArrayList<Double>(); PingDesc pingTask = (PingDesc) this.measurementDesc; String errorMsg = ""; MeasurementResult result = null; try { long totalPingDelay = 0; URL url = new URL("http://" + pingTask.target); int timeOut = (int) (3000 * (double) pingTask.pingTimeoutSec / Config.PING_COUNT_PER_MEASUREMENT); for (int i = 0; i < Config.PING_COUNT_PER_MEASUREMENT; i++) { pingStartTime = System.currentTimeMillis(); HttpURLConnection httpClient = (HttpURLConnection) url.openConnection(); httpClient.setRequestProperty("Connection", "close"); httpClient.setRequestMethod("HEAD"); httpClient.setReadTimeout(timeOut); httpClient.setConnectTimeout(timeOut); httpClient.connect(); pingEndTime = System.currentTimeMillis(); httpClient.disconnect(); rrts.add((double) (pingEndTime - pingStartTime)); this.progress = 100 * i / Config.PING_COUNT_PER_MEASUREMENT; broadcastProgressForUser(progress); } Logger.i("HTTP get ping succeeds"); Logger.i("RTT is " + rrts.toString()); double packetLoss = 1 - ((double) rrts.size() / (double) Config.PING_COUNT_PER_MEASUREMENT); result = constructResult(rrts, packetLoss, Config.PING_COUNT_PER_MEASUREMENT, PING_METHOD_HTTP); dataConsumed += pingTask.packetSizeByte * Config.PING_COUNT_PER_MEASUREMENT * 2; } catch (MalformedURLException e) { Logger.e(e.getMessage()); errorMsg += e.getMessage() + "\n"; } catch (IOException e) { Logger.e(e.getMessage()); errorMsg += e.getMessage() + "\n"; } if (result != null) { return result; } else { Logger.i("HTTP get ping fails"); throw new MeasurementError(errorMsg); } }