flush() 공개 메소드

public flush ( ) : void
리턴 void
예제 #1
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();
        }
예제 #2
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;
        }
        public void ShellAsync(string e, Action<string> y)
        {
#if AndroidShellAsync
            // http://www.android.pk/blog/general/launch-app-through-adb-shell/
            //  am start -a android.intent.action.MAIN -n com.android.settings/.Settings
            // am start tel:210-385-0098
            // am start -a android.intent.action.CALL tel:245007
            // am start -a android.intent.action.SENDTO "sms:5245007" -e "sms_body" "heyy"   && input keyevent 22 && input keyevent 66
            // am start -a android.intent.action.SENDTO -d sms:1234567890 --es sms_body ohai --ez exit_on_sent true
            // am start -a android.intent.action.SENDTO -d smsto:245007 --es sms_body ":*" --ez exit_on_sent true && am start -a android.intent.action.SENDTO -d sms:5245007 --es sms_body ":*" --ez exit_on_sent true && input keyevent 22 && input keyevent 66
            // pm list packages
            // pm list packages -f
        //http://stackoverflow.com/questions/11201659/android-adb-shell-dumpsys-tool
            // am start -S -e sms_body 'your message body' \
          //-e address receiver -t 'vnd.android-dir/mms-sms' \
          //com.android.mms/com.android.mms.ui.ComposeMessageActivity \
          //&& adb shell input keyevent 66

        //am start -n com.google.android.youtube/.PlayerActivity -d http://www.youtube.com/watch?v=MTT-crZBB0k
            // http://stackoverflow.com/questions/7095470/android-read-send-text-messages-on-ubuntu

            //         System.InvalidOperationException: Sequence contains more than one element
            //at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
            //at jsc.Languages.Java.JavaCompiler.GetArrayEnumeratorType() in x:\jsc.internal.svn\compiler\jsc\Languages\Java\JavaCompiler.overrride.cs:line 52
            //at jsc.Languages.Java.JavaCompiler.GetImportTypes(Type t, Boolean bExcludeJavaLang) in x:\jsc.internal.svn\compiler\jsc\Languages\Java\JavaCompiler.WriteImportTypes.cs:line 363
            //at jsc.Languages.Java.JavaCompiler.WriteImportTypes(Type ContextType) in x:\jsc.internal.svn\compiler\jsc\Languages\Java\JavaCompiler.WriteImportTypes.cs:line 22
            //at jsc.Languages.Java.JavaCompiler.CompileType(Type z) in x:\jsc.internal.svn\compiler\jsc\Languages\Java\JavaCompiler.CompileType.cs:line 43
            //at jsc.Languages.CompilerJob.<>c__DisplayClass1a.<CompileJava>b__17(Type xx) in x:\jsc.internal.svn\compiler\jsc\Languages\Java\CompilerJob.cs:line 120

            //            IsArrayEnumerator: ScriptCoreLib.Shared.BCLImplementation.System.__SZArrayEnumerator`1, ScriptCoreLibAndroid, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
            //IsArrayEnumerator: ScriptCoreLib.Shared.BCLImplementation.System.__SZArrayEnumerator`1, ScriptCoreLibJava, Version=4.1.0.0, Culture=neutral, PublicKeyToken=null


            try
            {
                // http://stackoverflow.com/questions/9062182/android-icmp-ping

                var p = new ProcessBuilder(new[] { "sh" }).redirectErrorStream(true).start();

                var os = new DataOutputStream(p.getOutputStream());
                //os.writeBytes(e + '\n');
                os.writeBytes(e + "\n");
                os.flush();

                // Close the terminal
                os.writeBytes("exit\n");
                os.flush();

                // read ping replys
                var reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
                string line = reader.readLine();


                while (line != null)
                {
                    y(line);
                    line = reader.readLine();
                }
            }
            catch (System.Exception ex)
            {
                y("AndroidShellAsync error: " + new { ex.Message });

            }

#elif ShellAsync
            try
            {
                var p = System.Diagnostics.Process.Start(
                    new ProcessStartInfo("cmd")
                    {

                        //ex = {"The Process object must have the UseShellExecute property set to false in order to redirect IO streams."}

                        UseShellExecute = false,

                        RedirectStandardInput = true,
                        RedirectStandardOutput = true,
                        RedirectStandardError = true
                    }

                    );
                y("pid: " + p.Id);
                y("");


                //ex = {"Timeouts are not supported on this stream."}
                //p.StandardOutput.BaseStream.ReadTimeout = 4000;
                //p.StandardError.BaseStream.ReadTimeout = 4000;

                var StandardOutput = "";
                var StandardError = "";

                p.StandardInput.WriteLine(e);
                p.StandardInput.WriteLine("exit");

                var ww = new AutoResetEvent(false);

                #region timeout
                var rr = new System.Threading.Thread(
                    delegate()
                    {
                        StandardOutput = p.StandardOutput.ReadToEnd();
                        StandardError = p.StandardError.ReadToEnd();

                        ww.Set();
                    }
                );

                rr.Start();
                #endregion


                #region timeout
                new System.Threading.Thread(
                    delegate()
                    {
                        System.Threading.Thread.Sleep(5000);


                        if (rr.IsAlive)
                        {
                            rr.Abort();
                        }
                        ww.Set();

                        //ex = {"Process must exit before requested information can be determined."}

                        if (p.HasExited)
                            return;


                        p.Kill();
                    }
                ).Start();
                #endregion

                System.Threading.Thread.Yield();

                ww.WaitOne();



                y(StandardOutput);
                y(StandardError);
                y("");
                y("exit: " + p.ExitCode);

            }
            catch (System.Exception ex)
            {

                Debugger.Break();
            }
            finally
            {
                y = null;
            }
#else
            y("ShellAsync not implemented.");
#endif

        }