Exemplo n.º 1
0
 /// <summary>
 /// TODO:这个方法 总是会报异常 原因不明确 ErrorException of type 'Java.Lang.RuntimeException' was thrown.
 /// </summary>
 /// <param name="path"></param>
 /// <returns></returns>
 public Bitmap getBitmap(string path)
 {
     try
     {
         Java.Net.URL url = new Java.Net.URL(path);
         LogManager.WriteSystemLog("Java.Net.URL url = new Java.Net.URL(path)");
         Java.Net.HttpURLConnection conn = (Java.Net.HttpURLConnection)url.OpenConnection();
         LogManager.WriteSystemLog("Java.Net.HttpURLConnection conn = (Java.Net.HttpURLConnection)url.OpenConnection();");
         conn.ConnectTimeout = 4000;
         conn.RequestMethod  = "GET";
         LogManager.WriteSystemLog(" conn.RequestMethod = GET;");
         if (conn.ResponseCode == Java.Net.HttpStatus.Ok)
         {
             LogManager.WriteSystemLog("status ok");
             Bitmap bitmap = BitmapFactory.DecodeStream(conn.InputStream);
             LogManager.WriteSystemLog(" conn.RequestMethod = GET;");
             return(bitmap);
         }
         else
         {
             var re = conn.ResponseCode;
             LogManager.WriteSystemLog("status not ok");
             // LogManager.WriteSystemLog("ReCode:" + re.ToString());
         }
     }
     catch (Exception ex)
     {
         // LogManager.WriteSystemLog("getBitmap:Error" + ex.stat);
     }
     return(null);
 }
Exemplo n.º 2
0
 public Bitmap getBitmap(string path)
 {
     try
     {
         Java.Net.URL url = new Java.Net.URL(path);
         Java.Net.HttpURLConnection conn = (Java.Net.HttpURLConnection)url.OpenConnection();
         conn.ConnectTimeout = 3000;
         conn.RequestMethod  = "GET";
         if (conn.ResponseCode == Java.Net.HttpStatus.Ok)
         {
             Bitmap bitmap = BitmapFactory.DecodeStream(conn.InputStream);
             return(bitmap);
         }
         else
         {
             var re = conn.ResponseCode;
             //算求来
         }
     }
     catch (Exception ex)
     {
         //LogManager.WriteSpeechErrorLog("getBitmap:Error" + ex.Message);
         Toast.MakeText(this, ex.Message, ToastLength.Long);
     }
     return(null);
 }
            protected override string RunInBackground(params string[] @params)
            {
                for (int i = 0; i <= 2; i++)
                {
                    try
                    {
                        String sourceFileUri = MainActivity.rec_video_uri[i];

                        Java.Net.HttpURLConnection conn = null;
                        DataOutputStream           dos  = null;
                        String lineEnd = "\r\n";
                        String twoHyphens = "--";
                        String boundary = "*****";
                        int    bytesRead, bytesAvailable, bufferSize;
                        byte[] buffer;
                        int    maxBufferSize = 1 * 1024 * 1024;
                        File   sourceFile    = new File(sourceFileUri);

                        if (sourceFile.IsFile)
                        {
                            try
                            {
                                String upLoadServerUri = "http://140.114.28.134/VideoUpload/uploads/upload.php";

                                // Ppen a URL connection to the Server
                                FileInputStream fileInputStream = new FileInputStream(
                                    sourceFile);
                                Java.Net.URL url = new Java.Net.URL(upLoadServerUri);

                                // Open a HTTP connection to the URL
                                conn               = (Java.Net.HttpURLConnection)url.OpenConnection();
                                conn.DoInput       = true;  // Allow Inputs
                                conn.DoOutput      = true;  // Allow Outputs
                                conn.UseCaches     = false; // Don't use a Cached Copy
                                conn.RequestMethod = "POST";
                                conn.SetRequestProperty("Connection", "Keep-Alive");
                                conn.SetRequestProperty("ENCTYPE", "multipart/form-data");
                                conn.SetRequestProperty("Content-Type",
                                                        "multipart/form-data;boundary=" + boundary);
                                conn.SetRequestProperty("upload_name", sourceFileUri);

                                dos = new DataOutputStream(conn.OutputStream);

                                dos.WriteBytes(twoHyphens + boundary + lineEnd);
                                dos.WriteBytes("Content-Disposition: form-data; name=\"upload_name\";filename=\""
                                               + sourceFileUri + "\"" + lineEnd);

                                dos.WriteBytes(lineEnd);

                                // Create a buffer of maximum size
                                bytesAvailable = fileInputStream.Available();

                                bufferSize = Math.Min(bytesAvailable, maxBufferSize);
                                buffer     = new byte[bufferSize];

                                // Read file and write
                                bytesRead = fileInputStream.Read(buffer, 0, bufferSize);

                                while (bytesRead > 0)
                                {
                                    dos.Write(buffer, 0, bufferSize);
                                    bytesAvailable = fileInputStream.Available();
                                    bufferSize     = Math
                                                     .Min(bytesAvailable, maxBufferSize);
                                    bytesRead = fileInputStream.Read(buffer, 0,
                                                                     bufferSize);
                                }

                                // Send multipart form data necesssary after file
                                dos.WriteBytes(lineEnd);
                                dos.WriteBytes(twoHyphens + boundary + twoHyphens
                                               + lineEnd);

                                // Responses from the server (code and message)
                                serverResponseCode = conn.ResponseCode;
                                String serverResponseMessage = conn
                                                               .ResponseMessage;

                                // Close the streams
                                fileInputStream.Close();
                                dos.Flush();
                                dos.Close();
                            }
                            catch (Exception e)
                            {
                                System.Console.WriteLine(e.ToString());
                            }
                        } // End if-else block
                    }
                    catch (Exception ex)
                    {
                        System.Console.WriteLine(ex.ToString());
                    }
                }
                progressDialog.Dismiss();

                return("Finished");
            }
        public Authorization Authenticate(HttpURLConnection request, ICredentials credentials)
        {
            if (parser == null)
                throw new InvalidOperationException ();
            if (request == null)
                return null;

            lastUse = DateTime.Now;
            var uri = new Uri (request.URL.ToString ());
            NetworkCredential cred = credentials.GetCredential (uri, "digest");
            if (cred == null)
                return null;

            string userName = cred.UserName;
            if (String.IsNullOrEmpty (userName))
                return null;

            string password = cred.Password;
            var auth = new StringBuilder ();
            auth.Append ($"Digest username=\"{userName}\", ");
            auth.Append ($"realm=\"{Realm}\", ");
            auth.Append ($"nonce=\"{Nonce}\", ");
            auth.Append ($"uri=\"{uri.PathAndQuery}\", ");

            if (Algorithm != null) { // hash algorithm (only MD5 in RFC2617)
                auth.Append ($"algorithm=\"{Algorithm}\", ");
            }

            auth.Append ($"response=\"{Response (userName, password, request)}\", ");

            if (QOP != null) { // quality of protection (server decision)
                auth.Append ($"qop=\"{QOP}\", ");
            }

            lock (this) {
                // _nc MUST NOT change from here...
                // number of request using this nonce
                if (QOP != null) {
                    auth.Append ($"nc={_nc.ToString ("X8")}, ");
                    _nc++;
                }
                // until here, now _nc can change
            }

            if (CNonce != null) // opaque value from the client
                auth.Append ($"cnonce=\"{CNonce}\", ");

            if (Opaque != null) // exact same opaque value as received from server
                auth.Append ($"opaque=\"{Opaque}\", ");

            auth.Length -= 2; // remove ", "
            return new Authorization (auth.ToString ());
        }
 string HA2(HttpURLConnection webRequest)
 {
     var uri = new Uri (webRequest.URL.ToString ());
     string ha2 = $"{webRequest.RequestMethod}:{uri.PathAndQuery}";
     if (QOP == "auth-int") {
         // TODO
         // ha2 += String.Format (":{0}", hentity);
     }
     return HashToHexString (ha2);
 }
 string Response(string username, string password, HttpURLConnection webRequest)
 {
     string response = $"{HA1 (username, password)}:{Nonce}:";
     if (QOP != null)
         response += $"{_nc.ToString ("X8")}:{CNonce}:{QOP}:";
     response += HA2 (webRequest);
     return HashToHexString (response);
 }
		void AddHeaders (HttpURLConnection conn, HttpHeaders headers)
		{
			if (headers == null)
				return;

			foreach (KeyValuePair<string, IEnumerable<string>> header in headers) {
				conn.SetRequestProperty (header.Key, header.Value != null ? String.Join (",", header.Value) : String.Empty);
			}
		}
		void SetupRequestBody (HttpURLConnection conn, HttpRequestMessage request)
		{
			if (request.Content == null) {
				// Pilfered from System.Net.Http.HttpClientHandler:SendAync
				if (HttpMethod.Post.Equals (request.Method) || HttpMethod.Put.Equals (request.Method) || HttpMethod.Delete.Equals (request.Method)) {
					// Explicitly set this to make sure we're sending a "Content-Length: 0" header.
					// This fixes the issue that's been reported on the forums:
					// http://forums.xamarin.com/discussion/17770/length-required-error-in-http-post-since-latest-release
					conn.SetRequestProperty ("Content-Length", "0");
				}
				return;
			}
			
			conn.DoOutput = true;
			long? contentLength = request.Content.Headers.ContentLength;
			if (contentLength != null)
				conn.SetFixedLengthStreamingMode ((int)contentLength);
			else
				conn.SetChunkedStreamingMode (0);
		}
		void HandlePreAuthentication (HttpURLConnection httpConnection)
		{
			AuthenticationData data = PreAuthenticationData;
			if (!PreAuthenticate || data == null)
				return;

			ICredentials creds = data.UseProxyAuthentication ? Proxy?.Credentials : Credentials;
			if (creds == null) {
				if (Logger.LogNet)
					Logger.Log (LogLevel.Info, LOG_APP, $"Authentication using scheme {data.Scheme} requested but no credentials found. No authentication will be performed");
				return;
			}

			IAndroidAuthenticationModule auth = data.Scheme == AuthenticationScheme.Unsupported ? data.AuthModule : authModules.Find (m => m?.Scheme == data.Scheme);
			if (auth == null) {
				if (Logger.LogNet)
					Logger.Log (LogLevel.Info, LOG_APP, $"Authentication module for scheme '{data.Scheme}' not found. No authentication will be performed");
				return;
			}

			Authorization authorization = auth.Authenticate (data.Challenge, httpConnection, creds);
			if (authorization == null) {
				if (Logger.LogNet)
					Logger.Log (LogLevel.Info, LOG_APP, $"Authorization module {auth.GetType ()} for scheme {data.Scheme} returned no authorization");
				return;
			}

			if (Logger.LogNet)
				Logger.Log (LogLevel.Info, LOG_APP, $"Authentication header '{data.UseProxyAuthentication ? "Proxy-Authorization" : "Authorization"}' will be set to '{authorization.Message}'");
			httpConnection.SetRequestProperty (data.UseProxyAuthentication ? "Proxy-Authorization" : "Authorization", authorization.Message);
		}
		/// <summary>
		/// Configure the <see cref="HttpURLConnection"/> before the request is sent. This method is meant to be overriden
		/// by applications which need to perform some extra configuration steps on the connection. It is called with all
		/// the request headers set, pre-authentication performed (if applicable) but before the request body is set 
		/// (e.g. for POST requests). The default implementation in AndroidClientHandler does nothing.
		/// </summary>
		/// <param name="request">Request data</param>
		/// <param name="conn">Pre-configured connection instance</param>
		protected virtual void SetupRequest (HttpRequestMessage request, HttpURLConnection conn)
		{
			AssertSelf ();
		}
		void CopyHeaders (HttpURLConnection httpConnection, HttpResponseMessage response)
		{
			IDictionary <string, IList <string>> headers = httpConnection.HeaderFields;
			foreach (string key in headers.Keys) {
				if (key == null) // First header entry has null key, it corresponds to the response message
					continue;

				HttpHeaders item_headers;
				string kind;
				if (known_content_headers.Contains (key)) {
					kind = "content";
					item_headers = response.Content.Headers;
				} else {
					kind = "response";
					item_headers = response.Headers;
				}
				item_headers.TryAddWithoutValidation (key, headers [key]);
			}
		}
		HttpResponseMessage DoProcessRequest (HttpRequestMessage request, HttpURLConnection httpConnection, CancellationToken cancellationToken)
		{
			if (Logger.LogNet)
				Logger.Log (LogLevel.Info, LOG_APP, $"{this}.DoProcessRequest ()");
			httpConnection.RequestMethod = request.Method.ToString ();
			try {
				if (Logger.LogNet)
					Logger.Log (LogLevel.Info, LOG_APP, $"  connecting");
				httpConnection.Connect ();
				if (Logger.LogNet)
					Logger.Log (LogLevel.Info, LOG_APP, $"  connected");
			} catch (Java.Net.ConnectException ex) {
				if (Logger.LogNet)
					Logger.Log (LogLevel.Info, LOG_APP, $"Connection exception {ex}");
				// Wrap it nicely in a "standard" exception so that it's compatible with HttpClientHandler
				throw new WebException (ex.Message, ex, WebExceptionStatus.ConnectFailure, null);
			}

			var statusCode = (HttpStatusCode)httpConnection.ResponseCode;
			var connectionUri = new Uri (httpConnection.URL.ToString ());

			// If the request was redirected we need to put the new URL in the request
			request.RequestUri = connectionUri;
			var ret = new AndroidHttpResponseMessage {
				RequestMessage = request,
				ReasonPhrase = httpConnection.ResponseMessage,
				StatusCode = statusCode,
			};

			if (Logger.LogNet)
				Logger.Log (LogLevel.Info, LOG_APP, $"Status code: {statusCode}");
			if (statusCode == HttpStatusCode.Unauthorized || statusCode == HttpStatusCode.ProxyAuthenticationRequired) {
				// We don't resend the request since that would require new set of credentials if the
				// ones provided in Credentials are invalid (or null) and that, in turn, may require asking the
				// user which is not something that should be taken care of by us and in this
				// context. The application should be responsible for this.
				// HttpClientHandler throws an exception in this instance, but I think it's not a good
				// idea. We'll return the response message with all the information required by the
				// application to fill in the blanks and provide the requested credentials instead.
				//
				// We should return the body of the response too but, alas, the Java client will throw
				// a, wait for it, FileNotFound exception if we attempt to access the input stream. So
				// no body, just a dummy. Java FTW!
				ret.Content = new StringContent ("Unauthorized", Encoding.ASCII);
				CopyHeaders (httpConnection, ret);

				if (ret.Headers.WwwAuthenticate != null) {
					ProxyAuthenticationRequested = false;
					CollectAuthInfo (ret.Headers.WwwAuthenticate);
				} else if (ret.Headers.ProxyAuthenticate != null) {
					ProxyAuthenticationRequested = true;
					CollectAuthInfo (ret.Headers.ProxyAuthenticate);
				}

				ret.RequestedAuthentication = RequestedAuthentication;
				return ret;
			}

			if (!IsErrorStatusCode (statusCode)) {
				if (Logger.LogNet)
					Logger.Log (LogLevel.Info, LOG_APP, $"Reading...");
				Stream inputStream = new BufferedStream (httpConnection.InputStream);
				if (decompress_here) {
					string[] encodings = httpConnection.ContentEncoding?.Split (',');
					if (encodings != null) {
						if (encodings.Contains (GZIP_ENCODING, StringComparer.OrdinalIgnoreCase))
							inputStream = new GZipStream (inputStream, CompressionMode.Decompress);
						else if (encodings.Contains (DEFLATE_ENCODING, StringComparer.OrdinalIgnoreCase))
							inputStream = new DeflateStream (inputStream, CompressionMode.Decompress);
					}
				}
				ret.Content = new StreamContent (inputStream);
			} else {
				if (Logger.LogNet)
					Logger.Log (LogLevel.Info, LOG_APP, $"Status code is {statusCode}, returning empty content");
				// For 400 >= response code <= 599 the Java client throws the FileNotFound exeption when attempting to read from the connection
				// Client tests require we return no content here
				ret.Content = new StringContent (String.Empty, Encoding.ASCII);
			}
			CopyHeaders (httpConnection, ret);

			IEnumerable <string> cookieHeaderValue;
			if (!UseCookies || CookieContainer == null || !ret.Headers.TryGetValues ("Set-Cookie", out cookieHeaderValue) || cookieHeaderValue == null) {
				if (Logger.LogNet)
					Logger.Log (LogLevel.Info, LOG_APP, $"No cookies");
				return ret;
			}

			try {
				if (Logger.LogNet)
					Logger.Log (LogLevel.Info, LOG_APP, $"Parsing cookies");
				CookieContainer.SetCookies (connectionUri, String.Join (",", cookieHeaderValue));
			} catch (Exception ex) {
				// We don't want to terminate the response because of a bad cookie, hence just reporting
				// the issue. We might consider adding a virtual method to let the user handle the
				// issue, but not sure if it's really needed. Set-Cookie header will be part of the
				// header collection so the user can always examine it if they spot an error.
				if (Logger.LogNet)
					Logger.Log (LogLevel.Info, LOG_APP, $"Failed to parse cookies in the server response. {ex.GetType ()}: {ex.Message}");
			}

			if (Logger.LogNet)
				Logger.Log (LogLevel.Info, LOG_APP, $"Returning");
			return ret;
		}
		async Task <HttpResponseMessage> ProcessRequest (HttpRequestMessage request, HttpURLConnection httpConnection, CancellationToken cancellationToken)
		{
			cancellationToken.ThrowIfCancellationRequested ();
			httpConnection.InstanceFollowRedirects = AllowAutoRedirect;
			RequestedAuthentication = null;
			ProxyAuthenticationRequested = false;
			
			return await Task<HttpResponseMessage>.Factory.StartNew (() => DoProcessRequest (request, httpConnection, cancellationToken), cancellationToken).ConfigureAwait (false);
		}