Inheritance: java.lang.Object, java.io.Serializable
Example #1
0
        public static string ToWebString(this Uri u)
        {
            var w = new StringBuilder();

            try
            {
                var url = new URL(u.ToString());
                var i = new InputStreamReader(url.openStream());
                var reader = new BufferedReader(i);

                var line = reader.readLine();
                while (line != null)
                {
                    w.AppendLine(line);

                    line = reader.readLine();
                }
                reader.close();
            }
            catch
            {
                // oops
            }

            return w.ToString();
        }
Example #2
0
        public string DownloadString(Uri u)
        {
            var w = new StringBuilder();

            try
            {
                var url    = new java.net.URL(u.ToString());
                var i      = new java.io.InputStreamReader(url.openStream(), "UTF-8");
                var reader = new java.io.BufferedReader(i);

                // can't we just read to the end?
                var line = reader.readLine();
                while (line != null)
                {
                    w.AppendLine(line);

                    line = reader.readLine();
                }
                reader.close();
            }
            catch
            {
                // oops
            }

            return(w.ToString());
        }
Example #3
0
 public override void run()
 {
     try
     {
         string s = NetLoginHandler.getServerId(loginHandler);
         var url =
             new URL(
                 (new StringBuilder()).append("http://www.minecraft.net/game/checkserver.jsp?user="******"&serverId=").append(s).toString());
         var bufferedreader = new BufferedReader(new InputStreamReader(url.openStream()));
         string s1 = bufferedreader.readLine();
         bufferedreader.close();
         if (s1.Equals("YES"))
         {
             NetLoginHandler.setLoginPacket(loginHandler, loginPacket);
         }
         else
         {
             loginHandler.kickUser("Failed to verify username!");
         }
     }
     catch (Exception exception)
     {
         exception.printStackTrace();
     }
 }
        static string InternalGetSDKVersion()
        {
            var version = "";
            var w = "";

            try
            {
                // by now we have webclient?
                // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201412/20141207
                var url = new java.net.URL(SDKVersionLocation);

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

                int CONNECT_TIMEOUT_MILL = 2000;
                int READ_TIMEOUT_MILL = 900;

                con.setConnectTimeout(CONNECT_TIMEOUT_MILL);
                con.setReadTimeout(READ_TIMEOUT_MILL);


                var i = new java.io.InputStreamReader(con.getInputStream(), "UTF-8");
                var reader = new java.io.BufferedReader(i);

                // can't we just read to the end?
                var line = reader.readLine();
                while (line != null)
                {
                    w += line;
                    w += "\n";

                    line = reader.readLine();
                }
                reader.close();
            }
            catch
            {
                // oops
            }
            //Log.wtf("HttpURLConnection", w);

            if (w.Length > 0)
            {
                var value = w;
                var offset = 0;

                var i = ((java.lang.String)(object)value).indexOf("version=\"", offset) + "version=\"".Length;
                var j = ((java.lang.String)(object)value).indexOf("\"", i);

                var ii = ((java.lang.String)(object)value).indexOf("version=\"", j) + "version=\"".Length;
                var jj = ((java.lang.String)(object)value).indexOf("\"", ii);

                version = ((java.lang.String)(object)value).substring(ii, jj);


            }
            return version;
        }
Example #5
0
        static string InternalGetSDKVersion()
        {
            var version = "";
            var w       = "";

            try
            {
                // by now we have webclient?
                // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201412/20141207
                var url = new java.net.URL(SDKVersionLocation);

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

                int CONNECT_TIMEOUT_MILL = 2000;
                int READ_TIMEOUT_MILL    = 900;

                con.setConnectTimeout(CONNECT_TIMEOUT_MILL);
                con.setReadTimeout(READ_TIMEOUT_MILL);


                var i      = new java.io.InputStreamReader(con.getInputStream(), "UTF-8");
                var reader = new java.io.BufferedReader(i);

                // can't we just read to the end?
                var line = reader.readLine();
                while (line != null)
                {
                    w += line;
                    w += "\n";

                    line = reader.readLine();
                }
                reader.close();
            }
            catch
            {
                // oops
            }
            //Log.wtf("HttpURLConnection", w);

            if (w.Length > 0)
            {
                var value  = w;
                var offset = 0;

                var i = ((java.lang.String)(object) value).indexOf("version=\"", offset) + "version=\"".Length;
                var j = ((java.lang.String)(object) value).indexOf("\"", i);

                var ii = ((java.lang.String)(object) value).indexOf("version=\"", j) + "version=\"".Length;
                var jj = ((java.lang.String)(object) value).indexOf("\"", ii);

                version = ((java.lang.String)(object) value).substring(ii, jj);
            }
            return(version);
        }
 public static void removeCodeBase(URL codeBase, URLClassLoader urlClassLoader)
 {
   ArrayList arrayList = new ArrayList();
   URL[] urLs = urlClassLoader.getURLs();
   for (int index = 0; index < urLs.Length; ++index)
   {
     if (!urLs[index].sameFile(codeBase))
       ((List) arrayList).add((object) urLs[index]);
   }
   ResourceBundleWrapper.noCodeBaseClassLoader = URLClassLoader.newInstance((URL[]) ((List) arrayList).toArray((object[]) new URL[0]));
 }
Example #7
0
        private string sendPOST(string POST_URL)
        {
            string            result = "";
            var               url    = new java.net.URL(POST_URL);
            HttpURLConnection con    = (HttpURLConnection)url.openConnection();

            con.setRequestMethod("GET");
            con.setRequestProperty("User-Agent", USER_AGENT);
            //for POST only -START
            con.setDoOutput(true);
            OutputStream os = con.getOutputStream();

            //os.write(POST_PARAMS.getBytes());
            //os.write(Encoding.UTF8.GetBytes(POST_PARAMS)); //??
            os.flush();
            os.close();
            //for POST only -END
            int responseCode = con.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK)
            { //success
                BufferedReader br = new BufferedReader(new InputStreamReader(
                                                           con.getInputStream()));
                string       inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = br.readLine()) != null)
                {
                    response.append(inputLine);
                }

                br.close();

                // print result
                result = response.toString();
            }
            else
            {
                Console.WriteLine("POST request not worked");
            }

            return(result);
        }
Example #8
0
 public virtual string getFileName(URL url)
 {
   string path = this.getPath(url);
   int num = String.instancehelper_lastIndexOf(path, "/");
   if (num < 0)
     return path;
   return String.instancehelper_substring(path, num + 1);
 }
Example #9
0
 /// <summary>
 /// Returns true if this package is sealed with respect to the specified code source url.
 /// </summary>
 public bool isSealed(URL url)
 {
     return default(bool);
 }
 /// <summary>
 /// Defines a package by name in this <tt>ClassLoader</tt>.
 /// </summary>
 protected Package definePackage(string name, string specTitle, string specVersion, string specVendor, string implTitle, string implVersion, string implVendor, URL sealBase)
 {
     return default(Package);
 }
		/// <summary>
		/// Obtains an audio input stream from the URL provided.
		/// </summary>
		static public AudioInputStream getAudioInputStream(URL @url)
		{
			return default(AudioInputStream);
		}
        protected virtual void addURL(URL url)
        {

        }
Example #13
0
        public byte[] UploadValues(Uri address, NameValueCollection data)
        {
            // http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
            // http://stackoverflow.com/questions/3038176/httpurlconnection-does-not-read-the-whole-respnse

            var addressString = address.ToString();
            //Console.WriteLine("enter UploadValues " + new { addressString });



            //             String urlParameters =
            //"fName=" + URLEncoder.encode("???", "UTF-8") +
            //"&lName=" + URLEncoder.encode("???", "UTF-8")

            var m = new MemoryStream();

            try
            {
                //Console.WriteLine("before urlParameters");
                #region urlParameters
                var urlParameters = new StringBuilder();

                //Implementation not found for type import :
                //type: System.Collections.Specialized.NameObjectCollectionBase
                //method: KeysCollection get_Keys()
                //Did you forget to add the [Script] attribute?
                //Please double check the signature!

                //foreach (string key in data.Keys)

                foreach (string key in data.AllKeys)
                {
                    if (urlParameters.Length > 0)
                    {
                        urlParameters.Append("&");
                    }


                    urlParameters.Append(
                        key + "=" + URLEncoder.encode(data[key], "UTF-8")
                        );
                }
                #endregion

                //Console.WriteLine("after urlParameters");

                //            Y:\staging\web\java\ScriptCoreLibJava\BCLImplementation\System\Net\__WebClient___c__DisplayClass2.java:60: error: unreported exception UnsupportedEncodingException; must be caught or declared to be thrown
                //builder0.Append(__String.Concat(string1, "=", URLEncoder.encode(this.data.get_Item(string1), "UTF-8")));
                //                                                               ^

                //Console.WriteLine(
                //    new { addressString }
                //);

                var url = new java.net.URL(addressString);

                // https://developer.android.com/training/articles/security-ssl.html

                var connection = (HttpURLConnection)url.openConnection();
                var https      = connection as HttpsURLConnection;
                if (https != null)
                {
                    Console.WriteLine(new { https });
                }


                connection.setUseCaches(false);
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setChunkedStreamingMode(0);

                // Numeric status code, 403: Forbidden

                // UserAgent:  Java/1.7.0_45
                //HtmlElement: Access denied | my.monese.com used CloudFlare to restrict access</title>
                //- Http: Request, POST /xml/GetCurrencyRateBasedOnString
                //   Command: POST
                // + URI: /xml/GetCurrencyRateBasedOnString
                //   ProtocolVersion: HTTP/1.1
                // + ContentType:  application/x-www-form-urlencoded
                //   Cache-Control:  no-cache
                //   Pragma:  no-cache
                //   UserAgent:  Java/1.7.0_45
                //   Host:  my.monese.com
                //   Accept:  text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
                //   Connection:  keep-alive
                //   ContentLength:  106
                //   HeaderEnd: CRLF

                //- Http: Request, POST /xml/GetCurrencyRateBasedOnString
                //   Command: POST
                // + URI: /xml/GetCurrencyRateBasedOnString
                //   ProtocolVersion: HTTP/1.1
                // + ContentType:  application/x-www-form-urlencoded
                //   Host:  my.monese.com
                //   ContentLength:  106
                //   Expect:  100-continue
                //   Connection:  Keep-Alive
                //   HeaderEnd: CRLF


                //                error { Message = Connection timed out: connect, StackTrace = java.net.ConnectException: Connection timed out: connect
                //at java.net.DualStackPlainSocketImpl.connect0(Native Method)

                connection.setRequestMethod("POST");

                // https://issues.jenkins-ci.org/browse/JENKINS-21033?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel
                // https://github.com/scalaj/scalaj-http/issues/27

                connection.setRequestProperty("User-Agent", "WebClient");
                connection.setRequestProperty("Accept", "application/xml");

                connection.setRequestProperty(
                    "Content-Type", "application/x-www-form-urlencoded"
                    );

                var bytes = Encoding.UTF8.GetBytes(
                    urlParameters.ToString()
                    );


                connection.setRequestProperty("Content-Length", "" + bytes.Length);

                //connection.setRequestProperty("Content-Language", "en-US");


                if (Headers != null)
                {
                    foreach (string key in Headers.AllKeys)
                    {
                        connection.addRequestProperty(key, Headers[key]);
                    }
                }

                //Console.WriteLine("before writeBytes " + new { bytes.Length });

                #region Send request
                var wr = new DataOutputStream(
                    connection.getOutputStream());

                wr.write((sbyte[])(object)bytes);

                //wr.writeBytes(urlParameters.ToString());
                wr.flush();
                #endregion

                //error { Message = Server returned HTTP response code: 403 for URL:
                //        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
                //        at ScriptCoreLibJava.BCLImplementation.System.Net.__WebClient___c__DisplayClass2._UploadValuesAsync_b__1(__WebClient___c__DisplayClass2.java:82)

                //Console.WriteLine("before Read ");

                // X:\jsc.svn\core\ScriptCoreLibJava\BCLImplementation\System\Net\WebClient.cs

                //Get Response
                // namespace java.io

                var asw = Stopwatch.StartNew();

                var ResponseCode = connection.getResponseCode();

                //Console.WriteLine("awaiting for input...");
                var xis = connection.getInputStream().ToNetworkStream();

                var buffer = new byte[0x4000];
                //var buffer = new byte[0x10000];

                // do we have to wait on android?
                //Console.WriteLine(new { xis.DataAvailable, asw.ElapsedMilliseconds });

                //var ss = xis.Read(buffer, 0, 0);

                //Console.WriteLine(new { ss, xis.DataAvailable, asw.ElapsedMilliseconds });


                //I/System.Console( 7821): { DataAvailable = false, ElapsedMilliseconds = 8278 }
                //I/System.Console( 7821): awaiting for input... { s = 2730 }
                //I/System.Console( 7821): awaiting for input... { s = 1340 }
                //I/System.Console( 7821): awaiting for input... { s = 438 }
                //I/System.Console( 7821): awaiting for input... { s = -1 }
                //I/System.Console( 7821): bytes: {{ Length = 4508 }}
                //I/System.Console( 7821): source: {{ Length = 4496 }}

                //I/System.Console(10970): { DataAvailable = true, ElapsedMilliseconds = 236 }
                //I/System.Console(10970): { ss = 0, DataAvailable = true, ElapsedMilliseconds = 237 }

                //var ok = true;

                while (xis.DataAvailable)
                //while (ok)
                {
                    var s = xis.Read(buffer, 0, buffer.Length);
                    //Console.WriteLine("awaiting for input... " + new { s });

                    //if (s < 0)
                    //{
                    //    ok = false;
                    //}
                    //else
                    if (s > 0)
                    {
                        m.Write(buffer, 0, s);
                    }
                }

                //wr.close();
                //xis.Close();
                if (connection != null)
                {
                    connection.disconnect();
                }
                //xis.Read(
                //xis.readall
            }
            catch (Exception ex)
            {
                //error { Message = failed to connect to apps.emta.ee/213.184.49.80 (port 80): connect failed: ETIMEDOUT (Connection timed out), StackTrace = java.net.ConnectException: failed to connect to apps.emta.ee/213.184.49.80 (port 80): connect failed: ETIMEDOUT (Connection timed out)
                //       at libcore.io.IoBridge.connect(IoBridge.java:114)
                //       at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
                //       at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
                //       at java.net.Socket.connect(Socket.java:843)
                //       at com.android.okhttp.internal.Platform.connectSocket(Platform.java:131)
                //       at com.android.okhttp.Connection.connect(Connection.java:101)
                //       at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:294)
                //       at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
                //       at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
                //       at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
                //       at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
                //       at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197)

                // ?
                Console.WriteLine("error " + new { ex.Message, ex.StackTrace });
            }

            //Thread.Sleep(666);
            var Result = m.ToArray();

            return(Result);
        }
 private static void EnsureResourceLocation(URL loc)
 {
     if (loc == null)
         throw new InvalidOperationException();
 }
		/// <summary>
		/// Sets the current URL being displayed.
		/// </summary>
		public void setPage(URL @page)
		{
		}
Example #16
0
        // one of the jobs of any class loader is to protect the system name space.
        // The normal ClassLoader heirarchy does address this by always delegating to the parent ClassLoader first,
        // thus ensuring that duplicate classes are not loaded

        // If you use custom ClassLoader, do not give the system one a chance to come into play.
        // http://blog.cyberborean.org/2007/07/04/custom-classloaders-the-black-art-of-java

        public InternalURLClassLoader(URL[] u, ClassLoader parent)
            : base(u, parent)
        {

        }
Example #17
0
 public virtual string createRelativeURL(URL url, URL baseURL)
 {
   if (url == null)
   {
     string str = "content url must not be null.";
     Throwable.__\u003CsuppressFillInStackTrace\u003E();
     throw new NullPointerException(str);
   }
   else if (baseURL == null)
   {
     string str = "baseURL must not be null.";
     Throwable.__\u003CsuppressFillInStackTrace\u003E();
     throw new NullPointerException(str);
   }
   else if (this.isFileStyleProtocol(url) && this.isSameService(url, baseURL))
   {
     List list1 = this.parseName(this.getPath(url));
     List list2 = this.parseName(this.getPath(baseURL));
     string query = this.getQuery(url);
     if (!this.isPath(baseURL))
       list2.remove(list2.size() - 1);
     if (url.equals((object) baseURL))
       return (string) list1.get(list1.size() - 1);
     int num1 = this.startsWithUntil(list1, list2);
     if (num1 == 0)
     {
       return url.toExternalForm();
     }
     else
     {
       if (num1 == list1.size())
         num1 += -1;
       ArrayList arrayList = new ArrayList();
       if (list2.size() >= list1.size())
       {
         int num2 = list2.size() - num1;
         for (int index = 0; index < num2; ++index)
           arrayList.add((object) "..");
       }
       arrayList.addAll((Collection) list1.subList(num1, list1.size()));
       return this.formatName((List) arrayList, query);
     }
   }
   else
     return url.toExternalForm();
 }
		/// <summary>
		/// Fetches a stream for the given URL, which is about to
		/// be loaded by the <code>setPage</code> method.
		/// </summary>
		protected InputStream getStream(URL @page)
		{
			return default(InputStream);
		}
Example #19
0
        public void StartJavaServer()
        {
            Console.WriteLine("Starting server");

            URL url = new URL("file:VehicleSystemServer.jar");
            URLClassLoader loader = new URLClassLoader(new[] {url});
            try
            {
                Class cl = Class.forName("VehicleSystemServer", true, loader);
                object obj = cl.newInstance();
                _server = (VehicleSystemServer) obj;

                String userName = Globals.GCM_SENDER_ID + "@gcm.googleapis.com";
                String password = Globals.GCM_SERVER_KEY;

                _server.connect(userName, password);

                MessageListener listener = new MessageListener(this);

                _server.addListener(listener);

                _server.testListener();

                Console.WriteLine("Server started successfully");
            }
            catch (Exception e)
            {
                Console.WriteLine("Error in starting server");
                Console.WriteLine(e.Message);
            }
        }
		/// <summary>
		/// Creates a <code>JEditorPane</code> based on a specified URL for input.
		/// </summary>
		public JEditorPane(URL @initialPage)
		{
		}
Example #21
0
        public string DownloadString(Uri u)
        {
            var w = new StringBuilder();

            try
            {
                var url = new java.net.URL(u.ToString());
                var i = new java.io.InputStreamReader(url.openStream(), "UTF-8");
                var reader = new java.io.BufferedReader(i);

                // can't we just read to the end?
                var line = reader.readLine();
                while (line != null)
                {
                    w.AppendLine(line);

                    line = reader.readLine();
                }
                reader.close();
            }
            catch
            {
                // oops
            }

            return w.ToString();
        }
Example #22
0
        public string UploadString(Uri u, string method, string data)
        {
            var w = new StringBuilder();

            HttpURLConnection conn = null;

            try
            {
                var url = new java.net.URL(u.ToString());

                conn = (HttpURLConnection)url.openConnection();
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setInstanceFollowRedirects(false);
                conn.setRequestMethod(method);
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.setRequestProperty("charset", "utf-8");
                conn.setRequestProperty("content-length", "" + data.Length);
                conn.setUseCaches(false);

                try
                {
                    if (Headers != null)
                    {
                        foreach (string key in Headers.AllKeys)
                        {
                            conn.addRequestProperty(key, Headers[key]);
                        }
                    }
                }
                catch (Exception e)
                {
                    //System.Console.WriteLine("ERROR: Failed to write headers. Exception was:" + e.Message);
                }

                DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
                wr.writeBytes(data);
                wr.flush();
                wr.close();



                //var i = new java.io.InputStreamReader(url.openStream(), "UTF-8");
                var i      = new java.io.InputStreamReader(conn.getInputStream(), "UTF-8");
                var reader = new java.io.BufferedReader(i);

                // can't we just read to the end?
                var line = reader.readLine();
                while (line != null)
                {
                    w.AppendLine(line);

                    line = reader.readLine();
                }
                reader.close();
            }
            catch
            {
                // oops
            }

            if (conn != null)
            {
                conn.disconnect();
            }

            return(w.ToString());
        }
Example #23
0
        public string UploadString(Uri u, string method, string data)
        {
            // http://hg.openjdk.java.net/jdk7/jdk7/jdk/file/tip/src/share/classes/sun/net/www/protocol/http/HttpURLConnection.java
            // fails on openJDK why?

            Console.WriteLine("enter UploadString " + new { u, method });

            var w = new StringBuilder();

            HttpURLConnection xHttpURLConnection = null;

            try
            {
                #region NSA is that you? intercept? we can only trust pinned off device certs
                var trustAllCerts = new[] { 
                    
                        new localX509TrustManager{}
                    };

                SSLContext sc = SSLContext.getInstance("SSL");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

                HttpsURLConnection.setDefaultHostnameVerifier(new localHostnameVerifier { });
                #endregion


                //UploadString getOutputStream
                //enter checkServerTrusted
                //enter getAcceptedIssuers
                //UploadString writeBytes

                var url = new java.net.URL(u.ToString());

                xHttpURLConnection = (HttpURLConnection)url.openConnection();



                var https = xHttpURLConnection as HttpsURLConnection;
                if (https != null)
                {
                    //Console.WriteLine(new { https });


                }


                //conn.setHostnameVerifier(new localHostnameVerifier { });

                xHttpURLConnection.setDoOutput(true);
                xHttpURLConnection.setDoInput(true);
                xHttpURLConnection.setInstanceFollowRedirects(false);
                //conn.setInstanceFollowRedirects(true);

                xHttpURLConnection.setRequestMethod(method);


                var xContentType = default(string);


                try
                {

                    if (Headers != null)
                    {
                        foreach (string key in Headers.AllKeys)
                        {
                            if (key == "Content-Type")
                            {
                                xContentType = Headers[key];
                            }


                            xHttpURLConnection.addRequestProperty(key, Headers[key]);
                        }
                    }
                }
                catch (Exception e)
                {
                    //System.Console.WriteLine("ERROR: Failed to write headers. Exception was:" + e.Message);
                }

                if (xContentType == null)
                {
                    xHttpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    xHttpURLConnection.setRequestProperty("charset", "utf-8");
                }

                //conn.setRequestProperty("content-length", "" + data.Length);
                xHttpURLConnection.setRequestProperty("Content-Length", "" + data.Length);

                xHttpURLConnection.setUseCaches(false);


                //Console.WriteLine("UploadString getOutputStream");
                var o = xHttpURLConnection.getOutputStream();

                //Console.WriteLine("UploadString writeBytes");

                // 
                DataOutputStream wr = new DataOutputStream(o);
                wr.writeBytes(data);
                //Console.WriteLine("UploadString flush");
                wr.flush();
                //Console.WriteLine("UploadString close");
                wr.close();


                //Console.WriteLine("UploadString readLine");

                //var i = new java.io.InputStreamReader(url.openStream(), "UTF-8");
                var i = new java.io.InputStreamReader(xHttpURLConnection.getInputStream(), "UTF-8");
                var reader = new java.io.BufferedReader(i);

                // can't we just read to the end?
                var line = reader.readLine();
                while (line != null)
                {
                    w.AppendLine(line);

                    line = reader.readLine();
                }
                reader.close();
            }
            catch (Exception err)
            {
                // 500 ?

                // = java.net.ProtocolException: Invalid HTTP method:

                // oops
                Console.WriteLine("UploadString " + new { err });
            }

            //Console.WriteLine("exit UploadString " + new { conn });

            if (xHttpURLConnection != null)
                xHttpURLConnection.disconnect();

            return w.ToString();
        }
		/// <summary>
		/// Obtains the audio file format of the specified URL.
		/// </summary>
		static public AudioFileFormat getAudioFileFormat(URL @url)
		{
			return default(AudioFileFormat);
		}
Example #25
0
        public byte[] UploadValues(Uri address, NameValueCollection data)
        {
            // http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
            // http://stackoverflow.com/questions/3038176/httpurlconnection-does-not-read-the-whole-respnse

            var addressString = address.ToString();
            //Console.WriteLine("enter UploadValues " + new { addressString });




            //             String urlParameters =
            //"fName=" + URLEncoder.encode("???", "UTF-8") +
            //"&lName=" + URLEncoder.encode("???", "UTF-8")

            var m = new MemoryStream();

            try
            {
                //Console.WriteLine("before urlParameters");
                #region urlParameters
                var urlParameters = new StringBuilder();

                //Implementation not found for type import :
                //type: System.Collections.Specialized.NameObjectCollectionBase
                //method: KeysCollection get_Keys()
                //Did you forget to add the [Script] attribute?
                //Please double check the signature!

                //foreach (string key in data.Keys)

                foreach (string key in data.AllKeys)
                {
                    if (urlParameters.Length > 0)
                        urlParameters.Append("&");


                    urlParameters.Append(
                        key + "=" + URLEncoder.encode(data[key], "UTF-8")
                    );

                }
                #endregion

                //Console.WriteLine("after urlParameters");

                //            Y:\staging\web\java\ScriptCoreLibJava\BCLImplementation\System\Net\__WebClient___c__DisplayClass2.java:60: error: unreported exception UnsupportedEncodingException; must be caught or declared to be thrown
                //builder0.Append(__String.Concat(string1, "=", URLEncoder.encode(this.data.get_Item(string1), "UTF-8")));
                //                                                               ^

                //Console.WriteLine(
                //    new { addressString }
                //);

                var url = new java.net.URL(addressString);

                // https://developer.android.com/training/articles/security-ssl.html

                var connection = (HttpURLConnection)url.openConnection();
                var https = connection as HttpsURLConnection;
                if (https != null)
                {
                    Console.WriteLine(new { https });
                }


                connection.setUseCaches(false);
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setChunkedStreamingMode(0);

                // Numeric status code, 403: Forbidden

                // UserAgent:  Java/1.7.0_45
                //HtmlElement: Access denied | my.monese.com used CloudFlare to restrict access</title>
                //- Http: Request, POST /xml/GetCurrencyRateBasedOnString 
                //   Command: POST
                // + URI: /xml/GetCurrencyRateBasedOnString
                //   ProtocolVersion: HTTP/1.1
                // + ContentType:  application/x-www-form-urlencoded
                //   Cache-Control:  no-cache
                //   Pragma:  no-cache
                //   UserAgent:  Java/1.7.0_45
                //   Host:  my.monese.com
                //   Accept:  text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
                //   Connection:  keep-alive
                //   ContentLength:  106
                //   HeaderEnd: CRLF

                //- Http: Request, POST /xml/GetCurrencyRateBasedOnString 
                //   Command: POST
                // + URI: /xml/GetCurrencyRateBasedOnString
                //   ProtocolVersion: HTTP/1.1
                // + ContentType:  application/x-www-form-urlencoded
                //   Host:  my.monese.com
                //   ContentLength:  106
                //   Expect:  100-continue
                //   Connection:  Keep-Alive
                //   HeaderEnd: CRLF


                //                error { Message = Connection timed out: connect, StackTrace = java.net.ConnectException: Connection timed out: connect
                //at java.net.DualStackPlainSocketImpl.connect0(Native Method)

                connection.setRequestMethod("POST");

                // https://issues.jenkins-ci.org/browse/JENKINS-21033?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel
                // https://github.com/scalaj/scalaj-http/issues/27

                connection.setRequestProperty("User-Agent", "WebClient");
                connection.setRequestProperty("Accept", "application/xml");

                connection.setRequestProperty(
                    "Content-Type", "application/x-www-form-urlencoded"
                     );

                var bytes = Encoding.UTF8.GetBytes(
                    urlParameters.ToString()
                );


                connection.setRequestProperty("Content-Length", "" + bytes.Length);

                //connection.setRequestProperty("Content-Language", "en-US");  


                if (Headers != null)
                {
                    foreach (string key in Headers.AllKeys)
                        connection.addRequestProperty(key, Headers[key]);
                }

                //Console.WriteLine("before writeBytes " + new { bytes.Length });

                #region Send request
                var wr = new DataOutputStream(
                            connection.getOutputStream());

                wr.write((sbyte[])(object)bytes);

                //wr.writeBytes(urlParameters.ToString());
                wr.flush();
                #endregion

                //error { Message = Server returned HTTP response code: 403 for URL: 
                //        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
                //        at ScriptCoreLibJava.BCLImplementation.System.Net.__WebClient___c__DisplayClass2._UploadValuesAsync_b__1(__WebClient___c__DisplayClass2.java:82)

                //Console.WriteLine("before Read ");

                // X:\jsc.svn\core\ScriptCoreLibJava\BCLImplementation\System\Net\WebClient.cs

                //Get Response	
                // namespace java.io

                var asw = Stopwatch.StartNew();

                var ResponseCode = connection.getResponseCode();

                //Console.WriteLine("awaiting for input...");
                var xis = connection.getInputStream().ToNetworkStream();

                var buffer = new byte[0x4000];
                //var buffer = new byte[0x10000];

                // do we have to wait on android?
                //Console.WriteLine(new { xis.DataAvailable, asw.ElapsedMilliseconds });

                //var ss = xis.Read(buffer, 0, 0);

                //Console.WriteLine(new { ss, xis.DataAvailable, asw.ElapsedMilliseconds });


                //I/System.Console( 7821): { DataAvailable = false, ElapsedMilliseconds = 8278 }
                //I/System.Console( 7821): awaiting for input... { s = 2730 }
                //I/System.Console( 7821): awaiting for input... { s = 1340 }
                //I/System.Console( 7821): awaiting for input... { s = 438 }
                //I/System.Console( 7821): awaiting for input... { s = -1 }
                //I/System.Console( 7821): bytes: {{ Length = 4508 }}
                //I/System.Console( 7821): source: {{ Length = 4496 }}

                //I/System.Console(10970): { DataAvailable = true, ElapsedMilliseconds = 236 }
                //I/System.Console(10970): { ss = 0, DataAvailable = true, ElapsedMilliseconds = 237 }

                //var ok = true;

                while (xis.DataAvailable)
                //while (ok)
                {
                    var s = xis.Read(buffer, 0, buffer.Length);
                    //Console.WriteLine("awaiting for input... " + new { s });

                    //if (s < 0)
                    //{
                    //    ok = false;
                    //}
                    //else 
                    if (s > 0)
                        m.Write(buffer, 0, s);
                }

                //wr.close();
                //xis.Close();
                if (connection != null)
                {
                    connection.disconnect();
                }
                //xis.Read(
                //xis.readall
            }
            catch (Exception ex)
            {
                //error { Message = failed to connect to apps.emta.ee/213.184.49.80 (port 80): connect failed: ETIMEDOUT (Connection timed out), StackTrace = java.net.ConnectException: failed to connect to apps.emta.ee/213.184.49.80 (port 80): connect failed: ETIMEDOUT (Connection timed out)
                //       at libcore.io.IoBridge.connect(IoBridge.java:114)
                //       at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
                //       at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
                //       at java.net.Socket.connect(Socket.java:843)
                //       at com.android.okhttp.internal.Platform.connectSocket(Platform.java:131)
                //       at com.android.okhttp.Connection.connect(Connection.java:101)
                //       at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:294)
                //       at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
                //       at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
                //       at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
                //       at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
                //       at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197)

                // ?
                Console.WriteLine("error " + new { ex.Message, ex.StackTrace });

            }

            //Thread.Sleep(666);
            var Result = m.ToArray();

            return Result;
        }
 ///// <summary>
 ///// Constructs a new URLClassLoader for the specified URLs, parent
 ///// class loader, and URLStreamHandlerFactory.
 ///// </summary>
 //public URLClassLoader(URL[] @urls, ClassLoader @parent, URLStreamHandlerFactory @factory)
 //{
 //}
 /// <summary>
 /// Constructs a new URLClassLoader for the given URLs.
 /// </summary>
 public URLClassLoader(URL[] @urls, ClassLoader @parent)
 {
 }
Example #27
0
        public string UploadString(Uri u, string method, string data)
        {
            // http://hg.openjdk.java.net/jdk7/jdk7/jdk/file/tip/src/share/classes/sun/net/www/protocol/http/HttpURLConnection.java
            // fails on openJDK why?

            Console.WriteLine("enter UploadString " + new { u, method });

            var w = new StringBuilder();

            HttpURLConnection xHttpURLConnection = null;

            try
            {
                #region NSA is that you? intercept? we can only trust pinned off device certs
                var trustAllCerts = new[] {
                    new localX509TrustManager {
                    }
                };

                SSLContext sc = SSLContext.getInstance("SSL");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

                HttpsURLConnection.setDefaultHostnameVerifier(new localHostnameVerifier {
                });
                #endregion


                //UploadString getOutputStream
                //enter checkServerTrusted
                //enter getAcceptedIssuers
                //UploadString writeBytes

                var url = new java.net.URL(u.ToString());

                xHttpURLConnection = (HttpURLConnection)url.openConnection();



                var https = xHttpURLConnection as HttpsURLConnection;
                if (https != null)
                {
                    //Console.WriteLine(new { https });
                }


                //conn.setHostnameVerifier(new localHostnameVerifier { });

                xHttpURLConnection.setDoOutput(true);
                xHttpURLConnection.setDoInput(true);
                xHttpURLConnection.setInstanceFollowRedirects(false);
                //conn.setInstanceFollowRedirects(true);

                xHttpURLConnection.setRequestMethod(method);


                var xContentType = default(string);


                try
                {
                    if (Headers != null)
                    {
                        foreach (string key in Headers.AllKeys)
                        {
                            if (key == "Content-Type")
                            {
                                xContentType = Headers[key];
                            }


                            xHttpURLConnection.addRequestProperty(key, Headers[key]);
                        }
                    }
                }
                catch (Exception e)
                {
                    //System.Console.WriteLine("ERROR: Failed to write headers. Exception was:" + e.Message);
                }

                if (xContentType == null)
                {
                    xHttpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    xHttpURLConnection.setRequestProperty("charset", "utf-8");
                }

                //conn.setRequestProperty("content-length", "" + data.Length);
                xHttpURLConnection.setRequestProperty("Content-Length", "" + data.Length);

                xHttpURLConnection.setUseCaches(false);


                //Console.WriteLine("UploadString getOutputStream");
                var o = xHttpURLConnection.getOutputStream();

                //Console.WriteLine("UploadString writeBytes");

                //
                DataOutputStream wr = new DataOutputStream(o);
                wr.writeBytes(data);
                //Console.WriteLine("UploadString flush");
                wr.flush();
                //Console.WriteLine("UploadString close");
                wr.close();


                //Console.WriteLine("UploadString readLine");

                //var i = new java.io.InputStreamReader(url.openStream(), "UTF-8");
                var i      = new java.io.InputStreamReader(xHttpURLConnection.getInputStream(), "UTF-8");
                var reader = new java.io.BufferedReader(i);

                // can't we just read to the end?
                var line = reader.readLine();
                while (line != null)
                {
                    w.AppendLine(line);

                    line = reader.readLine();
                }
                reader.close();
            }
            catch (Exception err)
            {
                // 500 ?

                // = java.net.ProtocolException: Invalid HTTP method:

                // oops
                Console.WriteLine("UploadString " + new { err });
            }

            //Console.WriteLine("exit UploadString " + new { conn });

            if (xHttpURLConnection != null)
            {
                xHttpURLConnection.disconnect();
            }

            return(w.ToString());
        }
 /// <summary>
 /// Creates a new instance of URLClassLoader for the specified
 /// URLs and parent class loader.
 /// </summary>
 public virtual URLClassLoader newInstance(URL[] @urls, ClassLoader @parent)
 {
     return default(URLClassLoader);
 }
 /// <summary>
 /// Constructor for the HttpURLConnection. </summary>
 /// <param name="u"> the URL </param>
 protected internal HttpURLConnection(URL u) : base(u)
 {
 }