//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: void ping() throws java.io.IOException internal virtual void Ping() { _pingCount++; IDictionary <string, string> usageDataMap = _collector.UdcParams; StringBuilder uri = new StringBuilder("http://" + _address + "/" + "?"); foreach (KeyValuePair <string, string> entry in usageDataMap.SetOfKeyValuePairs()) { uri.Append(entry.Key); uri.Append("="); uri.Append(URLEncoder.encode(entry.Value, StandardCharsets.UTF_8.name())); uri.Append("+"); } uri.Append(PING + "=").Append(_pingCount); URL url = new URL(uri.ToString()); URLConnection con = url.openConnection(); con.DoInput = true; con.DoOutput = false; con.UseCaches = false; con.connect(); con.InputStream.close(); }
private static string GetFileFromUrl(string fromUrl, string toFile) { try { URL url = new URL(fromUrl); URLConnection connection = url.OpenConnection(); connection.Connect(); //int fileLength = connection.GetContentLength(); // download the file InputStream input = new BufferedInputStream(url.OpenStream()); OutputStream output = new FileOutputStream(toFile); var data = new byte[1024]; long total = 0; int count; while ((count = input.Read(data)) != -1) { total += count; ////PublishProgress((int)(total * 100 / fileLength)); output.Write(data, 0, count); } output.Flush(); output.Close(); input.Close(); } catch (Exception e) { Log.Error("YourApp", e.Message); } return(toFile); }
/// <summary>Opens a url with read and connect timeouts</summary> /// <param name="url">URL to open</param> /// <param name="isSpnego">whether the url should be authenticated via SPNEGO</param> /// <returns>URLConnection</returns> /// <exception cref="System.IO.IOException"/> /// <exception cref="Org.Apache.Hadoop.Security.Authentication.Client.AuthenticationException /// "/> public virtual URLConnection OpenConnection(Uri url, bool isSpnego) { if (isSpnego) { if (Log.IsDebugEnabled()) { Log.Debug("open AuthenticatedURL connection" + url); } UserGroupInformation.GetCurrentUser().CheckTGTAndReloginFromKeytab(); AuthenticatedURL.Token authToken = new AuthenticatedURL.Token(); return(new AuthenticatedURL(new KerberosUgiAuthenticator(), connConfigurator).OpenConnection (url, authToken)); } else { if (Log.IsDebugEnabled()) { Log.Debug("open URL connection"); } URLConnection connection = url.OpenConnection(); if (connection is HttpURLConnection) { connConfigurator.Configure((HttpURLConnection)connection); } return(connection); } }
/// <summary> /// Downloads the resource with the specified URI to a local file. /// </summary> public void DownloadFile(URL address, string fileName) { URLConnection connection = null; InputStream inputStream = null; OutputStream outputStream = new FileOutputStream(fileName); try { connection = OpenConnection(address); inputStream = connection.InputStream; var buffer = new byte[BUFFER_SIZE]; int len; while ((len = inputStream.Read(buffer, 0, BUFFER_SIZE)) > 0) { outputStream.Write(buffer, 0, len); } outputStream.Flush(); } finally { if (inputStream != null) { inputStream.Close(); } var httpConnection = connection as HttpURLConnection; if (httpConnection != null) { httpConnection.Disconnect(); } outputStream.Close(); } }
/// <summary> /// Download a resource from the specified URI. /// </summary> public byte[] DownloadData(URL address) { URLConnection connection = null; InputStream inputStream = null; try { connection = OpenConnection(address); inputStream = connection.InputStream; var memStream = new ByteArrayOutputStream(); var buffer = new byte[BUFFER_SIZE]; int len; while ((len = inputStream.Read(buffer, 0, BUFFER_SIZE)) > 0) { memStream.Write(buffer, 0, len); } return(memStream.ToByteArray()); } finally { if (inputStream != null) { inputStream.Close(); } var httpConnection = connection as HttpURLConnection; if (httpConnection != null) { httpConnection.Disconnect(); } } }
protected override string RunInBackground(params string[] @params) { string strongPath = Android.OS.Environment.ExternalStorageDirectory.Path; string filePath = System.IO.Path.Combine(strongPath, "download.jpg"); int count; try { URL url = new URL(@params[0]); URLConnection connection = url.OpenConnection(); connection.Connect(); int LengthOfFile = connection.ContentLength; InputStream input = new BufferedInputStream(url.OpenStream(), LengthOfFile); OutputStream output = new FileOutputStream(filePath); byte[] data = new byte[1024]; long total = 0; while ((count = input.Read(data)) != -1) { total += count; PublishProgress("" + (int)((total / 100) / LengthOfFile)); output.Write(data, 0, count); } output.Flush(); output.Close(); input.Close(); } catch (Exception e) { } return(null); }
protected override string RunInBackground(params string[] @params) { var storagePath = Android.OS.Environment.ExternalStorageDirectory.Path; var filePath = System.IO.Path.Combine(storagePath, $"{fileName}.jpg"); try { URL url = new URL(@params[0]); URLConnection connection = url.OpenConnection(); connection.Connect(); int lengthOfFile = connection.ContentLength; InputStream input = new BufferedInputStream(url.OpenStream(), lengthOfFile); OutputStream output = new FileOutputStream(filePath); byte[] data = new byte[1024]; long total = 0; int count = 0; while ((count = input.Read(data)) != -1) { total += count; PublishProgress($"{(int)(total / 100) / lengthOfFile}"); output.Write(data, 0, count); } output.Flush(); output.Close(); input.Close(); return(string.Empty); } catch (Exception ex) { return(ex.Message); } }
// Send all queued messages if connected to the room. private void maybeDrainQueue() { lock (sendQueue) { if (appRTCSignalingParameters == null) { return; } try { foreach (string msg in sendQueue) { Log.Debug("console", msg); URLConnection connection = (new URL(appRTCSignalingParameters.gaeBaseHref + appRTCSignalingParameters.postMessageUrl)).OpenConnection(); connection.DoOutput = true; connection.OutputStream.Write(msg.GetBytes("UTF-8"), 0, msg.Length - 1); if (!connection.GetHeaderField(null).StartsWith("HTTP/1.1 200 ")) { throw new IOException("Non-200 response to POST: " + connection.GetHeaderField(null) + " for msg: " + msg); } } } catch (IOException e) { throw new Exception("Error", e); } sendQueue.Clear(); } }
/// <summary> /// Download a string from the specified URI. /// </summary> public string DownloadString(URL address) { URLConnection connection = null; InputStream inputStream = null; try { connection = OpenConnection(address); inputStream = connection.InputStream; var reader = new InputStreamReader(inputStream); var buffer = new char[BUFFER_SIZE]; var builder = new StringBuilder(); int len; while ((len = reader.Read(buffer, 0, BUFFER_SIZE)) > 0) { builder.Append(buffer, 0, len); } return(builder.ToString()); } finally { if (inputStream != null) { inputStream.Close(); } var httpConnection = connection as HttpURLConnection; if (httpConnection != null) { httpConnection.Disconnect(); } } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private java.io.InputStream openConnection(android.net.Uri uri) throws java.io.IOException private System.IO.Stream openConnection(Uri uri) { URL url = new URL(uri.ToString()); URLConnection conn = url.openConnection(); return(conn.InputStream); }
public Response <Bitmap> Load(Uri uri, bool localCacheOnly) { if (Build.VERSION.SdkInt >= BuildVersionCodes.IceCreamSandwich) { InstallCacheIfNeeded(m_Context); } URLConnection connection = OpenConnection(uri); connection.UseCaches = true; if (localCacheOnly) { connection.SetRequestProperty("Cache-Control", "only-if-cached,max-age=" + int.MaxValue); } var httpConnection = connection as HttpURLConnection; if (httpConnection != null) { int responseCode = (int)httpConnection.ResponseCode; if (responseCode >= 300) { httpConnection.Disconnect(); throw new ResponseException(responseCode + " " + httpConnection.ResponseMessage); } } long contentLength = connection.GetHeaderFieldInt("Content-Length", -1); bool fromCache = ParseResponseSourceHeader(connection.GetHeaderField(ResponseSource)); return(new Response <Bitmap>(connection.InputStream, fromCache, contentLength)); }
protected override byte[] RunInBackground(params string[] strings) { byte[] rv; try { URLConnection connection = (new URL(strings[0])).OpenConnection(); connection.Connect(); System.IO.Stream inputStream = connection.InputStream; System.IO.MemoryStream buffer = new System.IO.MemoryStream(); int nRead; byte[] data = new byte[16384]; while ((nRead = inputStream.Read(data, 0, data.Length)) != -1) { buffer.Write(data, 0, nRead); } buffer.Flush(); rv = buffer.ToArray(); buffer.Close(); inputStream.Close(); } catch (Java.Lang.Exception) { rv = null; } return(rv); }
/// <summary>access a url, ignoring some IOException such as the page does not exist</summary> /// <exception cref="System.IO.IOException"/> internal static void Access(string urlstring) { Log.Warn("access " + urlstring); Uri url = new Uri(urlstring); URLConnection connection = url.OpenConnection(); connection.Connect(); try { BufferedReader @in = new BufferedReader(new InputStreamReader(connection.GetInputStream ())); try { for (; @in.ReadLine() != null;) { } } finally { @in.Close(); } } catch (IOException ioe) { Log.Warn("urlstring=" + urlstring, ioe); } }
public virtual void TestPostKeysView() { Send("PUT", "/db", Status.Created, null); IDictionary <string, object> result; Database db = manager.GetDatabase("db"); View view = db.GetView("design/view"); view.SetMapAndReduce(new _Mapper_463(), null, "1"); IDictionary <string, object> key_doc1 = new Dictionary <string, object>(); key_doc1["parentId"] = "12345"; result = (IDictionary <string, object>)SendBody("PUT", "/db/key_doc1", key_doc1, Status .Created, null); view = db.GetView("design/view"); view.SetMapAndReduce(new _Mapper_475(), null, "1"); IList <object> keys = new AList <object>(); keys.AddItem("12345"); IDictionary <string, object> bodyObj = new Dictionary <string, object>(); bodyObj["keys"] = keys; URLConnection conn = SendRequest("POST", "/db/_design/design/_view/view", null, bodyObj ); result = (IDictionary <string, object>)ParseJSONResponse(conn); NUnit.Framework.Assert.AreEqual(1, result["total_rows"]); }
protected internal static Edu.Stanford.Nlp.Parser.Lexparser.ChineseLexiconAndWordSegmenter GetSegmenterDataFromSerializedFile(string serializedFileOrUrl) { Edu.Stanford.Nlp.Parser.Lexparser.ChineseLexiconAndWordSegmenter cs = null; try { log.Info("Loading segmenter from serialized file " + serializedFileOrUrl + " ..."); ObjectInputStream @in; InputStream @is; if (serializedFileOrUrl.StartsWith("http://")) { URL u = new URL(serializedFileOrUrl); URLConnection uc = u.OpenConnection(); @is = uc.GetInputStream(); } else { @is = new FileInputStream(serializedFileOrUrl); } if (serializedFileOrUrl.EndsWith(".gz")) { // it's faster to do the buffering _outside_ the gzipping as here @in = new ObjectInputStream(new BufferedInputStream(new GZIPInputStream(@is))); } else { @in = new ObjectInputStream(new BufferedInputStream(@is)); } cs = (Edu.Stanford.Nlp.Parser.Lexparser.ChineseLexiconAndWordSegmenter)@in.ReadObject(); @in.Close(); log.Info(" done."); return(cs); } catch (InvalidClassException ice) { // For this, it's not a good idea to continue and try it as a text file! log.Info(); // as in middle of line from above message throw new Exception(ice); } catch (FileNotFoundException fnfe) { // For this, it's not a good idea to continue and try it as a text file! log.Info(); // as in middle of line from above message throw new Exception(fnfe); } catch (StreamCorruptedException) { } catch (Exception e) { // suppress error message, on the assumption that we've really got // a text grammar, and that'll be tried next log.Info(); // as in middle of line from above message Sharpen.Runtime.PrintStackTrace(e); } return(null); }
/// <exception cref="System.IO.IOException"/> private static void ProcessUrl(Uri url) { URLConnection con = url.OpenConnection(); // con.setConnectTimeout(connectTimeout); // con.setReadTimeout(readTimeout); InputStream @in = con.GetInputStream(); // Read metadata Com.Drew.Metadata.Metadata metadata; try { metadata = ImageMetadataReader.ReadMetadata(@in); } catch (ImageProcessingException e) { // this is an error in the Jpeg segment structure. we're looking for bad handling of // metadata segments. in this case, we didn't even get a segment. System.Console.Error.Printf("%s: %s [Error Extracting Metadata]\n\t%s%n", e.GetType().FullName, url, e.Message); return; } catch (Exception t) { // general, uncaught exception during processing of jpeg segments System.Console.Error.Printf("%s: %s [Error Extracting Metadata]%n", t.GetType().FullName, url); Sharpen.Runtime.PrintStackTrace(t, System.Console.Error); return; } if (metadata.HasErrors()) { System.Console.Error.Println(url); foreach (Com.Drew.Metadata.Directory directory in metadata.GetDirectories()) { if (!directory.HasErrors()) { continue; } foreach (string error in directory.GetErrors()) { System.Console.Error.Printf("\t[%s] %s%n", directory.GetName(), error); } } } // Iterate through all values foreach (Com.Drew.Metadata.Directory directory_1 in metadata.GetDirectories()) { foreach (Tag tag in directory_1.GetTags()) { string tagName = tag.GetTagName(); string directoryName = directory_1.GetName(); string description = tag.GetDescription(); // truncate the description if it's too long if (description != null && description.Length > 1024) { description = Sharpen.Runtime.Substring(description, 0, 1024) + "..."; } System.Console.Out.Printf("[%s] %s = %s%n", directoryName, tagName, description); } } }
public override HttpURLConnection createConnection(URL arg0) { URL url = new URL("https://developer.huawei.com"); URLConnection rulConnection = url.openConnection(); HttpURLConnection httpUrlConnection = rulConnection.toType <HttpURLConnection>(); return(httpUrlConnection); }
//*************************************************************************************************** //******************FUNCION QUE SE ENCARGA DEL PROCESO DE DESCARGA DE ARCHIVO*********************** //*************************************************************************************************** void DescargaArchivo(ProgressCircleView tem_pcv, string url_archivo) { //OBTENEMOS LA RUTA DONDE SE ENCUENTRA LA CARPETA PICTURES DE NUESTRO DISPOSITIVO Y LE CONCTENAMOS //EL NOMBRE DE UNA CARPETA NUEVA CARPETA, ES AQUI DONDE GUADAREMOS EL ARCHIVO A DESCARGAR string filePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).AbsolutePath + "/DescargaImagen/"; Java.IO.File directory = new Java.IO.File(filePath); //VERIFICAMOS SI LA CARPETA EXISTE, SI NO LA CREAMOS if (directory.Exists() == false) { directory.Mkdir(); } //ESTABLECEMOS LA UBICACION DE NUESTRO ARCHIVO A DESCARGAR URL url = new URL(url_archivo); //CABRIMOS UNA CONEXION CON EL ARCHIVO URLConnection conexion = url.OpenConnection(); conexion.Connect(); //OBTENEMOS EL TAMAÑO DEL ARCHIVO A DESCARGAR int lenghtOfFile = conexion.ContentLength; //CREAMOS UN INPUTSTREAM PARA PODER EXTRAER EL ARCHIVO DE LA CONEXION InputStream input = new BufferedInputStream(url.OpenStream()); //ASIGNAMOS LA RUTA DONDE SE GUARDARA EL ARCHIVO, Y ASIGNAMOS EL NOMBRE CON EL QUE SE DESCARGAR EL ARCHIVO //PARA ESTE CASO CONSERVA EL MISMO NOMBRE string NewFile = directory.AbsolutePath + "/" + url_archivo.Substring(url_archivo.LastIndexOf("/") + 1); //CREAMOS UN OUTPUTSTREAM EN EL CUAL UTILIZAREMOS PARA CREAR EL ARCHIVO QUE ESTAMOS DESCARGANDO OutputStream output = new FileOutputStream(NewFile); byte[] data = new byte[lenghtOfFile]; long total = 0; int count; //COMENSAMOS A LEER LOS DATOS DE NUESTRO INPUTSTREAM while ((count = input.Read(data)) != -1) { total += count; //CON ESTA OPCION REPORTAMOS EL PROGRESO DE LA DESCARGA EN PORCENTAJE A NUESTRO CONTROL //QUE SE ENCUENTRA EN EL HILO PRINCIPAL RunOnUiThread(() => tem_pcv.setPorcentaje((int)((total * 100) / lenghtOfFile))); //ESCRIBIMOS LOS DATOS DELIDOS ES NUESTRO OUTPUTSTREAM output.Write(data, 0, count); } output.Flush(); output.Close(); input.Close(); //INDICAMOS A NUESTRO PROGRESS QUE SE HA COMPLETADO LA DESCARGA AL 100% RunOnUiThread(() => tem_pcv.setPorcentaje(100)); }
private static Bitmap DecodeBitmap(URLConnection connection) { connection.DoInput = true; connection.Connect(); var bitmap = BitmapFactory.DecodeStream(connection.InputStream); connection.Dispose(); return(bitmap); }
protected void setConnection(URLConnection conn) { _conn = conn; if (conn instanceof HttpURLConnection) { _httpConn = (HttpURLConnection)conn; } }
/// <exception cref="System.IO.IOException"></exception> internal override WalkRemoteObjectDatabase.FileStream Open(string path) { URLConnection c = this._enclosing.s3.Get(this._enclosing.bucket, this.ResolveKey( path)); InputStream raw = c.GetInputStream(); InputStream @in = this._enclosing.s3.Decrypt(c); int len = c.GetContentLength(); return(new WalkRemoteObjectDatabase.FileStream(@in, raw == @in ? len : -1)); }
private bool Validate(string bingMapsKey, ThinkGeo.MapSuite.Android.BingMapsMapType mapType) { bool result = false; URL url = null; Stream stream = null; URLConnection conn = null; string loginServiceTemplate = "http://dev.virtualearth.net/REST/v1/Imagery/Metadata/{0}?&incl=ImageryProviders&o=xml&key={1}"; try { string loginServiceUri = string.Format(CultureInfo.InvariantCulture, loginServiceTemplate, mapType, bingMapsKey); url = new URL(loginServiceUri); conn = url.OpenConnection(); stream = conn.InputStream; if (stream != null) { XmlDocument xDoc = new XmlDocument(); xDoc.Load(stream); XmlNamespaceManager nsmgr = new XmlNamespaceManager(xDoc.NameTable); nsmgr.AddNamespace("bing", "http://schemas.microsoft.com/search/local/ws/rest/v1"); XmlNode root = xDoc.SelectSingleNode("bing:Response", nsmgr); XmlNode imageUrlElement = root.SelectSingleNode("bing:ResourceSets/bing:ResourceSet/bing:Resources/bing:ImageryMetadata/bing:ImageUrl", nsmgr); XmlNodeList subdomainsElement = root.SelectNodes("bing:ResourceSets/bing:ResourceSet/bing:Resources/bing:ImageryMetadata/bing:ImageUrlSubdomains/bing:string", nsmgr); if (imageUrlElement != null && subdomainsElement != null) { result = true; } } } catch { } finally { if (url != null) { url.Dispose(); } if (conn != null) { conn.Dispose(); } if (stream != null) { stream.Dispose(); } } return(result); }
private string DownloadFile(string sUrl, string filePath) { try { //get result from uri URL url = new Java.Net.URL(sUrl); URLConnection connection = url.OpenConnection(); connection.Connect(); // this will be useful so that you can show a tipical 0-100% // progress bar int lengthOfFile = connection.ContentLength; // download the file InputStream input = new BufferedInputStream(url.OpenStream(), 8192); // Output stream Log.WriteLine(LogPriority.Info, "DownloadFile FilePath ", filePath); OutputStream output = new FileOutputStream(filePath); byte[] data = new byte[1024]; long total = 0; int count; while ((count = input.Read(data)) != -1) { total += count; // publishing the progress.... // After this onProgressUpdate will be called //publishProgress("" + (int)((total * 100) / lengthOfFile)); if (total % 10 == 10) //log for every 10th increment { Log.WriteLine(LogPriority.Info, "DownloadFile Progress ", "" + (int)((total * 100) / lengthOfFile)); } // writing data to file output.Write(data, 0, count); } // flushing output output.Flush(); // closing streams output.Close(); input.Close(); } catch (Exception ex) { Log.WriteLine(LogPriority.Error, "DownloadFile Error", ex.Message); } return(filePath); }
/// <summary> /// Given a URL connect stream positioned at the beginning of the /// representation of an object, this method reads that stream and /// creates an object that matches one of the types specified. /// /// The default implementation of this method should call getContent() /// and screen the return type for a match of the suggested types. /// </summary> /// <param name="urlc"> a URL connection. </param> /// <param name="classes"> an array of types requested </param> /// <returns> the object read by the {@code ContentHandler} that is /// the first match of the suggested types. /// null if none of the requested are supported. </returns> /// <exception cref="IOException"> if an I/O error occurs while reading the object. /// @since 1.3 </exception> //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @SuppressWarnings("rawtypes") public Object getContent(URLConnection urlc, Class[] classes) throws java.io.IOException //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: public virtual Object GetContent(URLConnection urlc, Class[] classes) { Object obj = GetContent(urlc); for (int i = 0; i < classes.Length; i++) { if (classes[i].isInstance(obj)) { return(obj); } } return(null); }
public virtual void TestTimeout() { Configuration conf = new Configuration(); URI uri = URI.Create("hftp://localhost"); HftpFileSystem fs = (HftpFileSystem)FileSystem.Get(uri, conf); URLConnection conn = fs.connectionFactory.OpenConnection(new Uri("http://localhost" )); NUnit.Framework.Assert.AreEqual(URLConnectionFactory.DefaultSocketTimeout, conn.GetConnectTimeout ()); NUnit.Framework.Assert.AreEqual(URLConnectionFactory.DefaultSocketTimeout, conn.GetReadTimeout ()); }
public static bool IsHostReachable(string host) { if (string.IsNullOrEmpty(host)) { return(false); } bool isReachable = true; Thread thread = new Thread(() => { try { //isReachable = InetAddress.GetByName(host).IsReachable(2000); /* * It's important to note that isReachable tries ICMP ping and then TCP echo (port 7). * These are often closed down on HTTP servers. * So a perfectly good working API with a web server on port 80 will be reported as unreachable * if ICMP and TCP port 7 are filtered out! * * Though we are not check it out */ //if (!isReachable){ URL url = new URL("http://" + host); URLConnection connection = url.OpenConnection(); //if(connection.ContentLength != -1){ //isReachable = true; if (connection.ContentLength == -1) { isReachable = false; } //} } catch (UnknownHostException e) { isReachable = false; } catch (IOException e) { isReachable = false; } }); thread.Start(); return(isReachable); }
protected internal virtual object SendBody(string method, string path, object bodyObj , int expectedStatus, object expectedResult) { URLConnection conn = SendRequest(method, path, null, bodyObj); object result = ParseJSONResponse(conn); Log.V(Tag, string.Format("%s %s --> %d", method, path, conn.GetResponseCode())); NUnit.Framework.Assert.AreEqual(expectedStatus, conn.GetResponseCode()); if (expectedResult != null) { NUnit.Framework.Assert.AreEqual(expectedResult, result); } return(result); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: public static java.io.InputStream getInputStreamFromURL(String paramString1, String paramString2, String paramString3) throws Exception public static Stream getInputStreamFromURL(string paramString1, string paramString2, string paramString3) { URL uRL = new URL(paramString1); URLConnection uRLConnection = uRL.openConnection(); uRLConnection.ConnectTimeout = 4000; uRLConnection.ReadTimeout = 30000; uRLConnection.setRequestProperty("User-agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.9) Gecko/20071025 Firefox/2.0.0.9"); if (!string.ReferenceEquals(paramString2, null)) { uRLConnection.setRequestProperty("Authorization", "Basic " + encode(paramString2 + ":" + paramString3)); } return(uRLConnection.InputStream); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: private static String getResponse(String serverAddress) throws java.io.IOException private static string GetResponse(string serverAddress) { string url = "http://" + serverAddress + "/metrics"; URLConnection connection = (new URL(url)).openConnection(); connection.DoOutput = true; connection.connect(); using (Scanner s = (new Scanner(connection.InputStream, "UTF-8")).useDelimiter("\\A")) { assertTrue(s.hasNext()); string ret = s.next(); assertFalse(s.hasNext()); return(ret); } }
// cluster /// <summary>Read in the content from a URL</summary> /// <param name="url">URL To read</param> /// <returns>the text from the output</returns> /// <exception cref="System.IO.IOException">if something went wrong</exception> private static string ReadOutput(Uri url) { StringBuilder @out = new StringBuilder(); URLConnection connection = url.OpenConnection(); BufferedReader @in = new BufferedReader(new InputStreamReader(connection.GetInputStream (), Charsets.Utf8)); string inputLine; while ((inputLine = @in.ReadLine()) != null) { @out.Append(inputLine); } @in.Close(); return(@out.ToString()); }