protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] @params) { if (!CommonService.CheckInternetConnection(activity.Context)) { return(null); } key = @params[0].ToString(); URL url = new URL(sqlquery_url); string query = ""; if (key == "GetMenuByRestoID") { query = MenuResto.GetByRestoID(@params[1].ToString()); } if (key == "GetMenuMakananByRestoID") { query = MenuResto.GetMenuMakananByRestoID(@params[1].ToString()); } if (key == "GetMenuMinumanByRestoID") { query = MenuResto.GetMenuMinumanByRestoID(@params[1].ToString()); } if (key == "GetMenuSpesialByRestoID") { query = MenuResto.GetMenuSpesialByRestoID(@params[1].ToString()); } if (key == "GetMenuByIDInSelect") { query = MenuResto.GetMenuByIDInSelect(@params[1].ToString()); } string data = URLEncoder.Encode("query", "UTF-8") + "=" + URLEncoder.Encode(query, "UTF-8"); HttpURLConnection urlConn = (HttpURLConnection)url.OpenConnection(); urlConn.RequestMethod = "POST"; urlConn.DoInput = true; urlConn.DoOutput = true; try { Stream oStream = urlConn.OutputStream; BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(oStream, "UTF-8")); bw.Write(data); bw.Flush(); bw.Close(); oStream.Close(); Stream iStream = urlConn.InputStream; BufferedReader br = new BufferedReader(new InputStreamReader(iStream)); System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(); string line = ""; while ((line = br.ReadLine()) != null) { stringBuilder.Append(line + "\n"); } urlConn.Disconnect(); string result = stringBuilder.ToString().Trim(); m_result = MenuResto.GetListByServerResponse(result); return(result); } catch (Java.IO.IOException ex) { // Toast.MakeText(activity.GetContext(), ex.Message, ToastLength.Short); } return(null); }
/// <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 Task SetupRequest(HttpRequestMessage request, HttpURLConnection conn) { return(Task.Factory.StartNew(AssertSelf)); }
/** Called when the activity is first created. */ protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); if (APP_ID == null) { Util.ShowAlert(this, "Warning", "Facebook Applicaton ID must be " + "specified before running this example: see Example.java"); } SetContentView(Resource.Layout.main); mLoginButton = (LoginButton)FindViewById(Resource.Id.login); mText = (TextView)FindViewById(Resource.Id.txt); mRequestButton = (Button)FindViewById(Resource.Id.requestButton); mPostButton = (Button)FindViewById(Resource.Id.postButton); mDeleteButton = (Button)FindViewById(Resource.Id.deletePostButton); mUploadButton = (Button)FindViewById(Resource.Id.uploadButton); mFacebook = new Facebook(APP_ID); mAsyncRunner = new AsyncFacebookRunner(mFacebook); SessionStore.Restore(mFacebook, this); SessionEvents.AddAuthListener(new SampleAuthListener(this)); SessionEvents.AddLogoutListener(new SampleLogoutListener(this)); mLoginButton.Init(this, mFacebook); mRequestButton.Click += delegate { mAsyncRunner.Request("me", new SampleRequestListener(this)); }; mRequestButton.Visibility = mFacebook.IsSessionValid ? ViewStates.Visible : ViewStates.Invisible; mUploadButton.Click += async delegate { Bundle parameters = new Bundle(); parameters.PutString("method", "photos.upload"); URL uploadFileUrl = null; try { uploadFileUrl = new URL( "http://www.facebook.com/images/devsite/iphone_connect_btn.jpg"); } catch (MalformedURLException e) { e.PrintStackTrace(); } try { HttpURLConnection conn = (HttpURLConnection)uploadFileUrl.OpenConnection(); conn.DoInput = true; await conn.ConnectAsync(); int length = conn.ContentLength; byte[] imgData = new byte[length]; var ins = conn.InputStream; await ins.ReadAsync(imgData, 0, imgData.Length); parameters.PutByteArray("picture", imgData); } catch (IOException e) { e.PrintStackTrace(); } mAsyncRunner.Request(null, parameters, "POST", new SampleUploadListener(this), null); }; mUploadButton.Visibility = mFacebook.IsSessionValid ? ViewStates.Visible : ViewStates.Invisible; mPostButton.Click += delegate { mFacebook.Dialog(this, "feed", new SampleDialogListener(this)); }; mPostButton.Visibility = mFacebook.IsSessionValid ? ViewStates.Visible : ViewStates.Invisible; }
bool HandleRedirect(HttpStatusCode redirectCode, HttpURLConnection httpConnection, RequestRedirectionState redirectState, out bool disposeRet) { if (!AllowAutoRedirect) { disposeRet = false; return(true); // We shouldn't follow and there's no data to fetch, just return } disposeRet = true; redirectState.NewUrl = null; redirectState.MethodChanged = false; switch (redirectCode) { case HttpStatusCode.MultipleChoices: // 300 break; case HttpStatusCode.Moved: // 301 case HttpStatusCode.Redirect: // 302 case HttpStatusCode.SeeOther: // 303 redirectState.MethodChanged = redirectState.Method != HttpMethod.Get; redirectState.Method = HttpMethod.Get; break; case HttpStatusCode.NotModified: // 304 disposeRet = false; return(true); // Not much happening here, just return and let the client decide // what to do with the response case HttpStatusCode.TemporaryRedirect: // 307 break; default: if ((int)redirectCode >= 300 && (int)redirectCode < 400) { throw new InvalidOperationException($"HTTP Redirection status code {redirectCode} ({(int)redirectCode}) not supported"); } return(false); } IDictionary <string, IList <string> > headers = httpConnection.HeaderFields; IList <string> locationHeader; if (!headers.TryGetValue("Location", out locationHeader) || locationHeader == null || locationHeader.Count == 0) { // As per https://tools.ietf.org/html/rfc7231#section-6.4.1 the reponse isn't required to contain the Location header and the // client should act accordingly. Since it is not documented what the action in this case should be, we're following what // Xamarin.iOS does and simply return the content of the request as if it wasn't a redirect. disposeRet = false; return(true); } if (locationHeader.Count > 1 && Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"More than one location header for HTTP {redirectCode} redirect. Will use the first one."); } redirectState.RedirectCounter++; if (redirectState.RedirectCounter >= MaxAutomaticRedirections) { throw new WebException($"Maximum automatic redirections exceeded (allowed {MaxAutomaticRedirections}, redirected {redirectState.RedirectCounter} times)"); } string redirectUrl = locationHeader [0]; string protocol = httpConnection.URL?.Protocol; if (redirectUrl.StartsWith("//", StringComparison.Ordinal)) { // When redirecting to an URL without protocol, we use the protocol of previous request // See https://tools.ietf.org/html/rfc3986#section-5 (example in section 5.4) redirectUrl = protocol + ":" + redirectUrl; } redirectState.NewUrl = new Uri(redirectUrl, UriKind.Absolute); if (Logger.LogNet) { Logger.Log(LogLevel.Debug, LOG_APP, $"Request redirected to {redirectState.NewUrl}"); } return(true); }
async Task <HttpResponseMessage> DoProcessRequest(HttpRequestMessage request, URL javaUrl, HttpURLConnection httpConnection, CancellationToken cancellationToken, RequestRedirectionState redirectState) { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"{this}.DoProcessRequest ()"); } try { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $" connecting"); } await httpConnection.ConnectAsync().ConfigureAwait(false); 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); } if (httpConnection.DoOutput) { await request.Content.CopyToAsync(httpConnection.OutputStream).ConfigureAwait(false); } 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(javaUrl, httpConnection) { RequestMessage = request, ReasonPhrase = httpConnection.ResponseMessage, StatusCode = statusCode, }; if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"Status code: {statusCode}"); } bool disposeRet; if (HandleRedirect(statusCode, httpConnection, redirectState, out disposeRet)) { if (disposeRet) { ret.Dispose(); ret = null; } return(ret); } switch (statusCode) { case HttpStatusCode.Unauthorized: case 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); }
/// <summary> /// Creates, configures and processes an asynchronous request to the indicated resource. /// </summary> /// <returns>Task in which the request is executed</returns> /// <param name="request">Request provided by <see cref="System.Net.Http.HttpClient"/></param> /// <param name="cancellationToken">Cancellation token.</param> protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { AssertSelf(); if (request == null) { throw new ArgumentNullException(nameof(request)); } if (!request.RequestUri.IsAbsoluteUri) { throw new ArgumentException("Must represent an absolute URI", "request"); } var redirectState = new RequestRedirectionState { NewUrl = request.RequestUri, RedirectCounter = 0, Method = request.Method }; while (true) { URL java_url = new URL(EncodeUrl(redirectState.NewUrl)); URLConnection java_connection; if (UseProxy) { java_connection = java_url.OpenConnection(await GetJavaProxy(redirectState.NewUrl, cancellationToken)); } else { java_connection = java_url.OpenConnection(Java.Net.Proxy.NoProxy); } var httpsConnection = java_connection as HttpsURLConnection; if (httpsConnection != null) { IHostnameVerifier hnv = GetSSLHostnameVerifier(httpsConnection); if (hnv != null) { httpsConnection.HostnameVerifier = hnv; } } if (ConnectTimeout != TimeSpan.Zero) { java_connection.ConnectTimeout = checked ((int)ConnectTimeout.TotalMilliseconds); } if (ReadTimeout != TimeSpan.Zero) { java_connection.ReadTimeout = checked ((int)ReadTimeout.TotalMilliseconds); } HttpURLConnection httpConnection = await SetupRequestInternal(request, java_connection).ConfigureAwait(continueOnCapturedContext: false);; HttpResponseMessage response = await ProcessRequest(request, java_url, httpConnection, cancellationToken, redirectState).ConfigureAwait(continueOnCapturedContext: false);; if (response != null) { return(response); } if (redirectState.NewUrl == null) { throw new InvalidOperationException("Request redirected but no new URI specified"); } request.Method = redirectState.Method; } }
protected virtual async Task WriteRequestContentToOutput(HttpRequestMessage request, HttpURLConnection httpConnection, CancellationToken cancellationToken) { using (var stream = await request.Content.ReadAsStreamAsync().ConfigureAwait(false)) { await stream.CopyToAsync(httpConnection.OutputStream, 4096, cancellationToken).ConfigureAwait(false); // // Rewind the stream to beginning in case the HttpContent implementation // will be accessed again (e.g. after redirect) and it keeps its stream // open behind the scenes instead of recreating it on the next call to // ReadAsStreamAsync. If we don't rewind it, the ReadAsStreamAsync // call above will throw an exception as we'd be attempting to read an // already "closed" stream (that is one whose Position is set to its // end). // // This is not a perfect solution since the HttpContent may do weird // things in its implementation, but it's better than copying the // content into a buffer since we have no way of knowing how the data is // read or generated and also we don't want to keep potentially large // amounts of data in memory (which would happen if we read the content // into a byte[] buffer and kept it cached for re-use on redirect). // // See https://bugzilla.xamarin.com/show_bug.cgi?id=55477 // if (stream.CanSeek) { stream.Seek(0, SeekOrigin.Begin); } } }
// No explicit connections are maintained. /// <exception cref="NGit.Errors.TransportException"></exception> /// <exception cref="System.NotSupportedException"></exception> private HttpURLConnection Connect(string service) { Uri u; try { StringBuilder b = new StringBuilder(); b.Append(baseUrl); if (b[b.Length - 1] != '/') { b.Append('/'); } b.Append(Constants.INFO_REFS); if (useSmartHttp) { b.Append(b.IndexOf("?") < 0 ? '?' : '&'); //$NON-NLS-1$ b.Append("service="); //$NON-NLS-1$ b.Append(service); } u = new Uri(b.ToString()); } catch (UriFormatException e) { throw new NotSupportedException(MessageFormat.Format(JGitText.Get().invalidURL, uri ), e); } try { int authAttempts = 1; for (; ;) { HttpURLConnection conn = HttpOpen(u); if (useSmartHttp) { string exp = "application/x-" + service + "-advertisement"; //$NON-NLS-1$ //$NON-NLS-2$ conn.SetRequestProperty(HttpSupport.HDR_ACCEPT, exp + ", */*"); } else { //$NON-NLS-1$ conn.SetRequestProperty(HttpSupport.HDR_ACCEPT, "*/*"); } //$NON-NLS-1$ int status = HttpSupport.Response(conn); switch (status) { case HttpURLConnection.HTTP_OK: { return(conn); } case HttpURLConnection.HTTP_NOT_FOUND: { throw new NoRemoteRepositoryException(uri, MessageFormat.Format(JGitText.Get().uriNotFound , u)); } case HttpURLConnection.HTTP_UNAUTHORIZED: { authMethod = HttpAuthMethod.ScanResponse(conn); if (authMethod == HttpAuthMethod.NONE) { throw new TransportException(uri, MessageFormat.Format(JGitText.Get().authenticationNotSupported , uri)); } if (1 < authAttempts || !authMethod.Authorize(uri, GetCredentialsProvider())) { throw new TransportException(uri, JGitText.Get().notAuthorized); } authAttempts++; continue; goto case HttpURLConnection.HTTP_FORBIDDEN; } case HttpURLConnection.HTTP_FORBIDDEN: { throw new TransportException(uri, MessageFormat.Format(JGitText.Get().serviceNotPermitted , service)); } default: { string err = status + " " + conn.GetResponseMessage(); //$NON-NLS-1$ throw new TransportException(uri, err); } } } } catch (NotSupportedException e) { throw; } catch (TransportException e) { throw; } catch (IOException e) { throw new TransportException(uri, MessageFormat.Format(JGitText.Get().cannotOpenService , service), e); } }
/// <exception cref="System.IO.IOException"></exception> internal virtual void Execute() { [email protected](); if (this.conn == null) { // Output hasn't started yet, because everything fit into // our request buffer. Send with a Content-Length header. // if ([email protected]() == 0) { throw new TransportException(this._enclosing.uri, JGitText.Get().startingReadStageWithoutWrittenRequestDataPendingIsNotSupported ); } // Try to compress the content, but only if that is smaller. TemporaryBuffer buf = new TemporaryBuffer.Heap(this._enclosing.http.postBuffer); try { GZIPOutputStream gzip = new GZIPOutputStream(buf); [email protected](gzip, null); gzip.Close(); if ([email protected]() < buf.Length()) { buf = this.@out; } } catch (IOException) { // Most likely caused by overflowing the buffer, meaning // its larger if it were compressed. Don't compress. buf = this.@out; } this.OpenStream(); if (buf != this.@out) { this.conn.SetRequestProperty(HttpSupport.HDR_CONTENT_ENCODING, HttpSupport.ENCODING_GZIP ); } this.conn.SetFixedLengthStreamingMode((int)buf.Length()); OutputStream httpOut = this.conn.GetOutputStream(); try { buf.WriteTo(httpOut, null); } finally { httpOut.Close(); } } [email protected](); int status = HttpSupport.Response(this.conn); if (status != HttpURLConnection.HTTP_OK) { throw new TransportException(this._enclosing.uri, status + " " + this.conn.GetResponseMessage ()); } //$NON-NLS-1$ string contentType = this.conn.GetContentType(); if (!this.responseType.Equals(contentType)) { this.conn.GetInputStream().Close(); throw this._enclosing.WrongContentType(this.responseType, contentType); } [email protected](this._enclosing.OpenInputStream(this.conn)); [email protected](this.execute); this.conn = null; }
/// <exception cref="System.IO.IOException"/> public HttpURLConnection Configure(HttpURLConnection conn) { NUnit.Framework.Assert.AreEqual(u, conn.GetURL()); conns.AddItem(conn); return(conn); }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="NGit.Errors.PackProtocolException"></exception> private FetchConnection NewDumbConnection(InputStream @in) { TransportHttp.HttpObjectDB d = new TransportHttp.HttpObjectDB(this, objectsUrl); BufferedReader br = ToBufferedReader(@in); IDictionary <string, Ref> refs; try { refs = d.ReadAdvertisedImpl(br); } finally { br.Close(); } if (!refs.ContainsKey(Constants.HEAD)) { // If HEAD was not published in the info/refs file (it usually // is not there) download HEAD by itself as a loose file and do // the resolution by hand. // HttpURLConnection conn = HttpOpen(new Uri(baseUrl, Constants.HEAD)); int status = HttpSupport.Response(conn); switch (status) { case HttpURLConnection.HTTP_OK: { br = ToBufferedReader(OpenInputStream(conn)); try { string line = br.ReadLine(); if (line != null && line.StartsWith(RefDirectory.SYMREF)) { string target = Sharpen.Runtime.Substring(line, RefDirectory.SYMREF.Length); Ref r = refs.Get(target); if (r == null) { r = new ObjectIdRef.Unpeeled(RefStorage.NEW, target, null); } r = new SymbolicRef(Constants.HEAD, r); refs.Put(r.GetName(), r); } else { if (line != null && ObjectId.IsId(line)) { Ref r = new ObjectIdRef.Unpeeled(RefStorage.NETWORK, Constants.HEAD, ObjectId.FromString (line)); refs.Put(r.GetName(), r); } } } finally { br.Close(); } break; } case HttpURLConnection.HTTP_NOT_FOUND: { break; } default: { throw new TransportException(uri, MessageFormat.Format(JGitText.Get().cannotReadHEAD , status, conn.GetResponseMessage())); } } } WalkFetchConnection wfc = new WalkFetchConnection(this, d); wfc.Available(refs); return(wfc); }
protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] sparams) { string method = sparams[0].ToString(); if (method.Equals("register")) { try { URL url = new URL(register_url); HttpURLConnection urlConn = (HttpURLConnection)url.OpenConnection(); urlConn.RequestMethod = "POST"; urlConn.DoInput = true; urlConn.DoOutput = true; Stream oStream = urlConn.OutputStream; BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(oStream, "UTF-8")); string name = sparams[1].ToString(); string email = sparams[2].ToString(); string phone = sparams[3].ToString(); string address = sparams[4].ToString(); string password = sparams[5].ToString(); // Log.e("LOG - NAME",name); //Log.e("LOG - email",email); string data = URLEncoder.Encode("name", "UTF-8") + "=" + URLEncoder.Encode(name, "UTF-8") + "&" + URLEncoder.Encode("email", "UTF-8") + "=" + URLEncoder.Encode(email, "UTF-8") + "&" + URLEncoder.Encode("phone", "UTF-8") + "=" + URLEncoder.Encode(phone, "UTF-8") + "&" + URLEncoder.Encode("address", "UTF-8") + "=" + URLEncoder.Encode(address, "UTF-8") + "&" + URLEncoder.Encode("password", "UTF-8") + "=" + URLEncoder.Encode(password, "UTF-8"); //Log.e("LOG","bw.write(data)"); bw.Write(data); bw.Flush(); bw.Close(); oStream.Close(); Stream iStream = urlConn.InputStream; BufferedReader br = new BufferedReader(new InputStreamReader(iStream)); System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(); string line = ""; // Log.e("LOG","line=br.readLine("); while ((line = br.ReadLine()) != null) { stringBuilder.Append(line + "\n"); } urlConn.Disconnect(); // Log.e("LOG","result: "+stringBuilder.ToString().trim()); try { Thread.Sleep(3000); } catch (InterruptedException e) { // e.printStackTrace(); } return(stringBuilder.ToString().Trim()); } catch (System.Exception x) { } } if (method.Equals("login")) { URL url = new URL(login_url); HttpURLConnection urlConn = (HttpURLConnection)url.OpenConnection(); urlConn.RequestMethod = "POST"; urlConn.DoInput = true; urlConn.DoOutput = true; Stream oStream = urlConn.OutputStream; BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(oStream, "UTF-8")); string email = sparams[1].ToString(); string password = sparams[2].ToString(); string data = URLEncoder.Encode("email", "UTF-8") + "=" + URLEncoder.Encode(email, "UTF-8") + "&" + URLEncoder.Encode("password", "UTF-8") + "=" + URLEncoder.Encode(password, "UTF-8"); //Log.e("LOG","bw.write(data)"); bw.Write(data); bw.Flush(); bw.Close(); oStream.Close(); try { Stream iStream = urlConn.InputStream; BufferedReader br = new BufferedReader(new InputStreamReader(iStream)); System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(); string line = ""; // Log.e("LOG","line=br.readLine("); while ((line = br.ReadLine()) != null) { stringBuilder.Append(line + "\n"); } urlConn.Disconnect(); // Log.e("LOG","result: "+stringBuilder.ToString().trim()); try { Thread.Sleep(3000); } catch (InterruptedException e) { // e.printStackTrace(); } return(stringBuilder.ToString().Trim()); } catch (System.Exception x) { Toast.MakeText(ctx, x.Message, ToastLength.Short); } } return(null); }
private void DownloadImage() { if (this.UriSource.IsAbsoluteUri && (this.UriSource.Scheme.ToLower() == "http" || this.UriSource.Scheme.ToLower() == "https")) { // download the image try { this.ImageLoadStatus = ImageStatus.Loading; HttpURLConnection connection = (HttpURLConnection) new Java.Net.URL(this.UriSource.ToString()).OpenConnection(); connection.Connect(); Stream dataStream = connection.InputStream; byte[] buf = new byte[1024]; byte[] outData; using (MemoryStream ms = new MemoryStream()) { int read; long length = connection.ContentLength; int percent = 0; int oldPercent = 0; int completeByte = 0; while ((read = dataStream.Read(buf, 0, buf.Length)) > 0) { oldPercent = percent; ms.Write(buf, 0, read); completeByte += buf.Length; percent = (int)((double)completeByte / (double)length * 100.0); if (oldPercent != percent) { this.DownloadProgress(this, new DownloadProgressEventArgs(percent)); } } percent = 100; this.DownloadProgress(this, new DownloadProgressEventArgs(percent)); outData = ms.ToArray(); } this.Image = BitmapFactory.DecodeByteArray(outData, 0, outData.Length, CreateBitmapOptions()); this.ImageLoadStatus = ImageStatus.Loaded; this.ImageOpened(this, new RoutedEventArgs() { OriginalSource = this }); } catch (Exception e) { this.ImageLoadStatus = ImageStatus.Failed; this.ImageFailed(this, new ExceptionRoutedEventArgs(e) { ErrorMessage = "Image can not be opened." }); } } else { string path = this.UriSource.IsAbsoluteUri ? this.UriSource.AbsolutePath : this.UriSource.ToString(); if (System.IO.File.Exists(path)) { // load the image from the local storage try { this.ImageLoadStatus = ImageStatus.Loading; this.Image = BitmapFactory.DecodeFile(path, CreateBitmapOptions()); this.ImageLoadStatus = ImageStatus.Loaded; this.ImageOpened(this, new RoutedEventArgs() { OriginalSource = this }); } catch (Exception e) { this.ImageLoadStatus = ImageStatus.Failed; this.ImageFailed(this, new ExceptionRoutedEventArgs(e) { ErrorMessage = "Image can not be opened." }); } } else { this.ImageLoadStatus = ImageStatus.Loading; if (path[0] == '/') { path = path.Substring(1, path.Length - 1); } // try to load the image from Resources var packageName = Application.Context.PackageName.ToLower(); var resourceName = string.Format("{0}:drawable/{1}", packageName, path.Split('.')[0].ToLower()); var id = Application.Context.Resources.GetIdentifier(resourceName, null, null); if (id != 0) { try { var contentPath = string.Format("android.resource://{0}/drawable/{1}", packageName, id); var androidUrl = Android.Net.Uri.Parse(contentPath); using (var imageStream = Application.Context.ContentResolver.OpenInputStream(androidUrl)) { this.Image = BitmapFactory.DecodeStream(imageStream, new Rect(), this.CreateBitmapOptions()); } this.ImageLoadStatus = ImageStatus.Loaded; this.ImageOpened(this, new RoutedEventArgs() { OriginalSource = this }); return; } catch (Exception e) { Debug.WriteLine(e.ToString()); } } // load the image from Assets try { using (var imageStream = Application.Context.Assets.Open(path)) { this.Image = BitmapFactory.DecodeStream(imageStream, new Rect(), this.CreateBitmapOptions()); } this.ImageLoadStatus = ImageStatus.Loaded; this.ImageOpened(this, new RoutedEventArgs() { OriginalSource = this }); } catch (Exception e) { this.ImageLoadStatus = ImageStatus.Failed; this.ImageFailed(this, new ExceptionRoutedEventArgs(e) { ErrorMessage = "Image can not be opened." }); } } } }
protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] @params) { Stream imageIn; try { imageIn = mActivity.ContentResolver.OpenInputStream(mImageUri); } catch (Java.IO.FileNotFoundException e) { Log.Error(TAG, "could not open Stream", e); return(null); } HttpURLConnection conn = null; Stream responseIn = null; try { conn = (HttpURLConnection) new URL(UPLOAD_URL).OpenConnection(); conn.DoOutput = true; ImgurAuthorization.GetInstance().AddToHttpURLConnection(conn); Stream outstream = conn.OutputStream; Copy(imageIn, outstream); // set image outstream.Flush(); outstream.Close(); if (conn.ResponseCode == Java.Net.HttpStatus.Ok) // execute api call { responseIn = conn.InputStream; return(OnInput(responseIn)); } else { Log.Info(TAG, "responseCode=" + conn.ResponseCode); responseIn = conn.ErrorStream; StringBuilder sb = new StringBuilder(); Scanner scanner = new Scanner(responseIn); while (scanner.HasNext) { sb.Append(scanner.Next()); } Log.Info(TAG, "error response: " + sb.ToString()); return(null); } } catch (Exception ex) { Log.Error(TAG, "Error during POST", ex); return(null); } finally { try { responseIn.Close(); } catch (Exception ignore) { } try { conn.Disconnect(); } catch (Exception ignore) { } try { imageIn.Close(); } catch (Exception ignore) { } // delete temp file ImageAdapter.DeleteTempFile(); } }
public void GetMethod(String url) { Task.Run(async() => { LinearLayout linearLayout = FindViewById <LinearLayout>(Resource.Id.linearLayout); HttpClient client = new HttpClient(); String ip = GetString(Resource.String.ip); String contentfolder = "Pliki pobrane"; String path = this.GetExternalFilesDir(null).AbsolutePath; Android.Util.Log.Error("path", path); File file = new File(); var result = await client.GetAsync(url); var json = await result.Content.ReadAsStringAsync(); if (result.IsSuccessStatusCode) { List <File> files = Newtonsoft.Json.JsonConvert.DeserializeObject <List <File> >(json); int i = 0; int b = 0; var layouty = new List <LinearLayout>(); for (var j = 0; j < files.Count; j++) { int k = j; System.Console.WriteLine("to jest j: " + j); System.Console.WriteLine("wtf " + files.Count); LinearLayout linear = (LinearLayout)LayoutInflater.Inflate(Resource.Layout.materialy, linearLayout, false); System.Diagnostics.Debug.WriteLine("jacie " + j); System.Diagnostics.Debug.WriteLine("jaciek " + k); ((TextView)linear.FindViewById(Resource.Id.idt)).Text = "Plik numer " + (j + 1) + " o nazwie " + files[k].filename; layouty.Add(linear); Button downloadb = linear.FindViewById <Button>(Resource.Id.downloadb); Button deleteb = linear.FindViewById <Button>(Resource.Id.deletefb); Button filestatsb = linear.FindViewById <Button>(Resource.Id.filestatsb); if (rank.Equals("1")) { deleteb.Visibility = ViewStates.Invisible; } downloadb.Click += (sender, e) => { System.Console.WriteLine("kliknalem"); View view = (View)sender; Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this); builder.SetTitle("Pobieranie pliku"); builder.SetMessage("Czy na pewno chcesz pobrac?"); builder.SetPositiveButton("Tak", OkAction); builder.SetNegativeButton("Nie", CancelAction); var myCustomDialog = builder.Create(); System.Diagnostics.Debug.WriteLine("w downloadzie " + k); myCustomDialog.Show(); async void OkAction(object sender, DialogClickEventArgs e) { builder.Dispose(); System.Console.WriteLine("ok"); Button myButton = sender as Button; System.Console.WriteLine("tu"); TextView liczbapobrant = linear.FindViewById <TextView>(Resource.Id.liczbapobrant); int liczbapobran = int.Parse(liczbapobrant.Text); for (int i = 1; i <= liczbapobran; i++) { System.Console.WriteLine(liczbapobran.ToString()); } if (!System.IO.Directory.Exists(path + contentfolder)) { System.IO.Directory.CreateDirectory(path + "/" + contentfolder); System.Console.WriteLine("Stworzono folder"); } bar = new ProgressDialog(this); bar.SetProgressStyle(ProgressDialogStyle.Horizontal); bar.Max = (liczbapobran); bar.Progress = 0; bar.Show(); ilepobrac = liczbapobran; numerpobierania = 0; String text = null; String filename = files[k].filename; for (int i = 1; i <= liczbapobran; i++) { using (WebClient wc = new WebClient()) { var watch = System.Diagnostics.Stopwatch.StartNew(); wc.DownloadFile(new Uri(ip + "/file/download/" + files[k].id), path + "/" + contentfolder + "/" + files[k].filename); float czasdownload = 0; long roznicaping = 0; float avgping = 0; watch.Stop(); czasdownload = watch.ElapsedTicks; bar.Progress = bar.Progress + (bar.Max / ilepobrac); numerpobierania++; if (numerpobierania == ilepobrac) { bar.Dismiss(); text = "Plik pobrano " + ilepobrac + " razy i zapisano w folderze " + contentfolder; Toast.MakeText(Application.Context, text, ToastLength.Long).Show(); } URL url = new URL(ip + "/ping/"); float m; for (m = 1; m <= 10; m++) { watch = System.Diagnostics.Stopwatch.StartNew(); HttpURLConnection urlConnection = (HttpURLConnection)url.OpenConnection(); urlConnection.ConnectTimeout = 1000; urlConnection.ReadTimeout = 1000; watch.Stop(); var po = watch.ElapsedTicks; roznicaping += po; urlConnection.Disconnect(); System.Diagnostics.Debug.WriteLine(roznicaping / 10000); } avgping = roznicaping / m / 10000; czasdownload = czasdownload / 10000; System.Diagnostics.Debug.WriteLine("Tyle czasu pobieram: " + czasdownload); string urlstats = ip + "/file/updatestats/"; Pola.File filestat = new Pola.File(); filestat.temp_avg_latency = avgping; filestat.temp_download_time = czasdownload; filestat.temp_platform = GetString(Resource.String.jezyk); filestat.id = files[k].id; filestat.temp_filename = files[k].filename; filestat.temp_username = username; client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); var jsonpost = JsonConvert.SerializeObject(filestat); var content = new StringContent(jsonpost, Encoding.UTF8, "application/json"); string coto = await content.ReadAsStringAsync(); System.Diagnostics.Debug.WriteLine("coto: " + coto); var responsepost = await client.PutAsync(urlstats + filestat.id, content); System.Diagnostics.Debug.WriteLine("Statystyka numer " + numerpobierania); } } } void CancelAction(object sender, DialogClickEventArgs e) { builder.Dispose(); } }; deleteb.Click += (sender, e) => { View view = (View)sender; Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this); builder.SetTitle("Usunięcie materiału"); builder.SetMessage("Czy na pewno usunąć ten materiał?"); builder.SetPositiveButton("Tak", OkAction); builder.SetNegativeButton("Nie", CancelAction); var myCustomDialog = builder.Create(); myCustomDialog.Show(); async void OkAction(object sender, DialogClickEventArgs e) { HttpClient client = new HttpClient(); System.Console.WriteLine("takie ip: " + ip + "/file/delete/" + files[k].id); var result = await client.DeleteAsync(ip + "/file/delete/" + files[k].id); var json = await result.Content.ReadAsStringAsync(); if (result.IsSuccessStatusCode) { Toast.MakeText(Application.Context, "Usunięto plik", ToastLength.Long).Show(); Finish(); StartActivity(Intent); } else { Toast.MakeText(Application.Context, "Wystąpił błąd", ToastLength.Long).Show(); } builder.Dispose(); } void CancelAction(object sender, DialogClickEventArgs e) { builder.Dispose(); } }; filestatsb.Click += (sender, e) => { View view = (View)sender; Intent StatystykiPliku = new Intent(this, typeof(StatystykiPliku)); StatystykiPliku.PutExtra("username", username); StatystykiPliku.PutExtra("rank", rank); StatystykiPliku.PutExtra("fileid", files[k].id.ToString()); StartActivity(StatystykiPliku); }; //newtask.Wait(); //}); } rysuj(layouty, linearLayout); } //}).Wait(); }); }
public virtual void TestWebServiceAccess() { ApplicationSubmissionContextInfo app = new ApplicationSubmissionContextInfo(); string appid = "application_123_0"; app.SetApplicationId(appid); string submitAppRequestBody = TestRMWebServicesDelegationTokenAuthentication.GetMarshalledAppInfo (app); Uri url = new Uri("http://localhost:8088/ws/v1/cluster/apps"); HttpURLConnection conn = (HttpURLConnection)url.OpenConnection(); // we should be access the apps page with the static user TestRMWebServicesDelegationTokenAuthentication.SetupConn(conn, "GET", string.Empty , string.Empty); try { conn.GetInputStream(); NUnit.Framework.Assert.AreEqual(ClientResponse.Status.Ok.GetStatusCode(), conn.GetResponseCode ()); } catch (IOException) { NUnit.Framework.Assert.Fail("Got " + conn.GetResponseCode() + " instead of 200 accessing " + url.ToString()); } conn.Disconnect(); // new-application, submit app and kill should fail with // forbidden IDictionary <string, TestRMWebServicesHttpStaticUserPermissions.Helper> urlRequestMap = new Dictionary <string, TestRMWebServicesHttpStaticUserPermissions.Helper>(); string killAppRequestBody = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" + "<appstate>\n" + " <state>KILLED</state>\n" + "</appstate>"; urlRequestMap["http://localhost:8088/ws/v1/cluster/apps"] = new TestRMWebServicesHttpStaticUserPermissions.Helper ("POST", submitAppRequestBody); urlRequestMap["http://localhost:8088/ws/v1/cluster/apps/new-application"] = new TestRMWebServicesHttpStaticUserPermissions.Helper ("POST", string.Empty); urlRequestMap["http://localhost:8088/ws/v1/cluster/apps/app_123_1/state"] = new TestRMWebServicesHttpStaticUserPermissions.Helper ("PUT", killAppRequestBody); foreach (KeyValuePair <string, TestRMWebServicesHttpStaticUserPermissions.Helper> entry in urlRequestMap) { Uri reqURL = new Uri(entry.Key); conn = (HttpURLConnection)reqURL.OpenConnection(); string method = entry.Value.method; string body = entry.Value.requestBody; TestRMWebServicesDelegationTokenAuthentication.SetupConn(conn, method, "application/xml" , body); try { conn.GetInputStream(); NUnit.Framework.Assert.Fail("Request " + entry.Key + "succeeded but should have failed" ); } catch (IOException) { NUnit.Framework.Assert.AreEqual(ClientResponse.Status.Forbidden.GetStatusCode(), conn.GetResponseCode()); InputStream errorStream = conn.GetErrorStream(); string error = string.Empty; BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream, "UTF8" )); for (string line; (line = reader.ReadLine()) != null;) { error += line; } reader.Close(); errorStream.Close(); NUnit.Framework.Assert.AreEqual("The default static user cannot carry out this operation." , error); } conn.Disconnect(); } }
public AndroidHttpResponseMessage(URL javaUrl, HttpURLConnection httpConnection) { this.javaUrl = javaUrl; this.httpConnection = httpConnection; }
}// ctor // --------------------------------------------------------------------------- public override void doTrailingDataReadCallback(InputStream inputStream, CollabrifyResponse_PB responseWrapper, Response_GetEventBatch_PB responseObject, HttpURLConnection connection)
Task DisconnectAsync(HttpURLConnection httpConnection) { return(Task.Run(() => httpConnection?.Disconnect())); }
/// <exception cref="System.IO.IOException"/> /// <exception cref="Org.Apache.Hadoop.Security.Authentication.Client.AuthenticationException /// "/> private IDictionary DoDelegationTokenOperation <_T0>(Uri url, AuthenticatedURL.Token token, DelegationTokenAuthenticator.DelegationTokenOperation operation, string renewer, Org.Apache.Hadoop.Security.Token.Token <_T0> dToken, bool hasResponse, string doAsUser) where _T0 : TokenIdentifier { IDictionary ret = null; IDictionary <string, string> @params = new Dictionary <string, string>(); @params[OpParam] = operation.ToString(); if (renewer != null) { @params[RenewerParam] = renewer; } if (dToken != null) { @params[TokenParam] = dToken.EncodeToUrlString(); } // proxyuser if (doAsUser != null) { @params[DelegationTokenAuthenticatedURL.DoAs] = URLEncoder.Encode(doAsUser, "UTF-8" ); } string urlStr = url.ToExternalForm(); StringBuilder sb = new StringBuilder(urlStr); string separator = (urlStr.Contains("?")) ? "&" : "?"; foreach (KeyValuePair <string, string> entry in @params) { sb.Append(separator).Append(entry.Key).Append("=").Append(URLEncoder.Encode(entry .Value, "UTF8")); separator = "&"; } url = new Uri(sb.ToString()); AuthenticatedURL aUrl = new AuthenticatedURL(this, connConfigurator); HttpURLConnection conn = aUrl.OpenConnection(url, token); conn.SetRequestMethod(operation.GetHttpMethod()); HttpExceptionUtils.ValidateResponse(conn, HttpURLConnection.HttpOk); if (hasResponse) { string contentType = conn.GetHeaderField(ContentType); contentType = (contentType != null) ? StringUtils.ToLowerCase(contentType) : null; if (contentType != null && contentType.Contains(ApplicationJsonMime)) { try { ObjectMapper mapper = new ObjectMapper(); ret = mapper.ReadValue <IDictionary>(conn.GetInputStream()); } catch (Exception ex) { throw new AuthenticationException(string.Format("'%s' did not handle the '%s' delegation token operation: %s" , url.GetAuthority(), operation, ex.Message), ex); } } else { throw new AuthenticationException(string.Format("'%s' did not " + "respond with JSON to the '%s' delegation token operation" , url.GetAuthority(), operation)); } } return(ret); }
async Task <HttpResponseMessage> DoProcessRequest(HttpRequestMessage request, URL javaUrl, HttpURLConnection httpConnection, CancellationToken cancellationToken, RequestRedirectionState redirectState) { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"{this}.DoProcessRequest ()"); } if (cancellationToken.IsCancellationRequested) { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, " cancelled"); } cancellationToken.ThrowIfCancellationRequested(); } try { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $" connecting"); } await ConnectAsync(httpConnection, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); 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); } if (cancellationToken.IsCancellationRequested) { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, " cancelled"); } await DisconnectAsync(httpConnection).ConfigureAwait(continueOnCapturedContext: false); cancellationToken.ThrowIfCancellationRequested(); } CancellationTokenRegistration cancelRegistration = default(CancellationTokenRegistration); HttpStatusCode statusCode = HttpStatusCode.OK; Uri connectionUri = null; try { cancelRegistration = cancellationToken.Register(() => { DisconnectAsync(httpConnection).ContinueWith(t => { if (t.Exception != null) { Logger.Log(LogLevel.Info, LOG_APP, $"Disconnection exception: {t.Exception}"); } }, TaskScheduler.Default); }, useSynchronizationContext: false); if (httpConnection.DoOutput) { await WriteRequestContentToOutput(request, httpConnection, cancellationToken); } statusCode = await Task.Run(() => (HttpStatusCode)httpConnection.ResponseCode).ConfigureAwait(false); connectionUri = new Uri(httpConnection.URL.ToString()); } finally { cancelRegistration.Dispose(); } if (cancellationToken.IsCancellationRequested) { await DisconnectAsync(httpConnection).ConfigureAwait(continueOnCapturedContext: false); cancellationToken.ThrowIfCancellationRequested(); } // If the request was redirected we need to put the new URL in the request request.RequestUri = connectionUri; var ret = new AndroidHttpResponseMessage(javaUrl, httpConnection) { RequestMessage = request, ReasonPhrase = httpConnection.ResponseMessage, StatusCode = statusCode, }; if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"Status code: {statusCode}"); } if (!IsErrorStatusCode(statusCode)) { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"Reading..."); } ret.Content = GetContent(httpConnection, httpConnection.InputStream); } else { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"Status code is {statusCode}, reading..."); } // For 400 >= response code <= 599 the Java client throws the FileNotFound exception when attempting to read from the input stream. // Instead we try to read the error stream and return an empty string if the error stream isn't readable. ret.Content = GetErrorContent(httpConnection, new StringContent(String.Empty, Encoding.ASCII)); } bool disposeRet; if (HandleRedirect(statusCode, httpConnection, redirectState, out disposeRet)) { if (redirectState.MethodChanged) { // If a redirect uses GET but the original request used POST with content, then the redirected // request will fail with an exception. // There's also no way to send content using GET (except in the URL, of course), so discarding // request.Content is what we should do. // // See https://github.com/xamarin/xamarin-android/issues/1282 if (redirectState.Method == HttpMethod.Get) { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"Discarding content on redirect"); } request.Content = null; } } if (disposeRet) { ret.Dispose(); ret = null; } else { CopyHeaders(httpConnection, ret); ParseCookies(ret, connectionUri); } // We don't want to pass the authorization header onto the next location request.Headers.Authorization = null; return(ret); } switch (statusCode) { case HttpStatusCode.Unauthorized: case 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 return the body of the response too, but the Java client will throw // a FileNotFound exception if we attempt to access the input stream. // Instead we try to read the error stream and return an default message if the error stream isn't readable. ret.Content = GetErrorContent(httpConnection, 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); } CopyHeaders(httpConnection, ret); ParseCookies(ret, connectionUri); if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"Returning"); } return(ret); }
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())); }
/// <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 Task SetupRequest(HttpRequestMessage request, HttpURLConnection conn) { Action a = AssertSelf; return(Task.Run(a)); }
/// <summary> /// 心跳请求 /// </summary> public void HeartBeat() { try { // 创建HTTP连接 using (HttpURLConnection httpConn = Settings.url.OpenConnection() as HttpURLConnection) { httpConn.RequestMethod = "POST"; // 启用POST方式 httpConn.UseCaches = false; // 不启用缓存 httpConn.DoOutput = true; // 启用输出流 httpConn.DoInput = true; // 启用输入流 httpConn.InstanceFollowRedirects = true; // 启用HTTP重定向 //httpConn.SetRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 设置请求类型 httpConn.SetRequestProperty("Content-Type", "application/json"); // 设置请求类型 httpConn.ConnectTimeout = 10000; // 设置超时时间 // 获取输出流 using (DataOutputStream outStream = new DataOutputStream(httpConn.OutputStream)) { // 格式化心跳参数 if (!Settings.HeartBeatParams.Has("action")) { Settings.HeartBeatParams.Put("action", "AdSubAppHeartBeat"); } if (!Settings.HeartBeatParams.Has("cpuId")) { //Settings.HeartBeatParams.Put("cpuId", Settings.CpuId); Settings.HeartBeatParams.Put("cpuId", "666999"); } if (!Settings.HeartBeatParams.Has("version")) { Settings.HeartBeatParams.Put("version", Settings.Version); } outStream.WriteBytes(Settings.HeartBeatParams.ToString().Replace("\r", "").Replace("\n", "").Replace(" ", "")); // 将数据写入输出流 Settings.HeartBeatParams.Remove("lastCmd"); Settings.HeartBeatParams.Remove("errMsg"); outStream.Flush(); // 立刻输出缓存数据 } // 判断是否响应成功 if (httpConn.ResponseCode == HttpStatus.Ok) { using (InputStreamReader inStream = new InputStreamReader(httpConn.InputStream)) // 获取输入流 using (BufferedReader buffer = new BufferedReader(inStream)) // 获取输入流读取器 { string inputLine = null, heartBeatResult = null; while ((inputLine = buffer.ReadLine()) != null) { heartBeatResult += inputLine + "\n"; } // 解析心跳返回数据 ParseHeartBeatResult(heartBeatResult); } } else { long Code = (long)httpConn.ResponseCode; // HTTP error RunOnUiThread(() => { Toast.MakeText(this, "心跳线程: HTTP error code " + Code, ToastLength.Long).Show(); }); } httpConn.Disconnect(); // 断开HTTP连接 } } catch (Exception e) { System.Console.WriteLine("HeartBeat Exception: " + e.Message); } }
bool HandleRedirect(HttpStatusCode redirectCode, HttpURLConnection httpConnection, RequestRedirectionState redirectState, out bool disposeRet) { if (!AllowAutoRedirect) { disposeRet = false; return(true); // We shouldn't follow and there's no data to fetch, just return } disposeRet = true; redirectState.NewUrl = null; switch (redirectCode) { case HttpStatusCode.MultipleChoices: // 300 break; case HttpStatusCode.Moved: // 301 case HttpStatusCode.Redirect: // 302 case HttpStatusCode.SeeOther: // 303 redirectState.Method = HttpMethod.Get; break; case HttpStatusCode.TemporaryRedirect: // 307 break; default: if ((int)redirectCode >= 300 && (int)redirectCode < 400) { throw new InvalidOperationException($"HTTP Redirection status code {redirectCode} ({(int)redirectCode}) not supported"); } return(false); } IDictionary <string, IList <string> > headers = httpConnection.HeaderFields; IList <string> locationHeader; if (!headers.TryGetValue("Location", out locationHeader) || locationHeader == null || locationHeader.Count == 0) { throw new InvalidOperationException($"HTTP connection redirected with code {redirectCode} ({(int)redirectCode}) but no Location header found in response"); } if (locationHeader.Count > 1 && Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"More than one location header for HTTP {redirectCode} redirect. Will use the first one."); } redirectState.RedirectCounter++; if (redirectState.RedirectCounter >= MaxAutomaticRedirections) { throw new WebException($"Maximum automatic redirections exceeded (allowed {MaxAutomaticRedirections}, redirected {redirectState.RedirectCounter} times)"); } Uri location = new Uri(locationHeader [0], UriKind.Absolute); redirectState.NewUrl = location; if (Logger.LogNet) { Logger.Log(LogLevel.Debug, LOG_APP, $"Request redirected to {location}"); } return(true); }
async Task <HttpResponseMessage> DoProcessRequest(HttpRequestMessage request, URL javaUrl, HttpURLConnection httpConnection, CancellationToken cancellationToken, RequestRedirectionState redirectState) { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"{this}.DoProcessRequest ()"); } if (cancellationToken.IsCancellationRequested) { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, " cancelled"); } cancellationToken.ThrowIfCancellationRequested(); } CancellationTokenSource waitHandleSource = new CancellationTokenSource(); try { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $" connecting"); } CancellationToken linkedToken = CancellationTokenSource.CreateLinkedTokenSource(waitHandleSource.Token, cancellationToken).Token; await Task.WhenAny( httpConnection.ConnectAsync(), Task.Run(() => { linkedToken.WaitHandle.WaitOne(); if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"Wait handle task finished"); } })) .ConfigureAwait(false); 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); } finally{ //If not already cancelled, cancel the WaitOne through the waitHandleSource to prevent an orphaned thread waitHandleSource.Cancel(); } if (cancellationToken.IsCancellationRequested) { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, " cancelled"); } await DisconnectAsync(httpConnection).ConfigureAwait(continueOnCapturedContext: false); cancellationToken.ThrowIfCancellationRequested(); } CancellationTokenRegistration cancelRegistration = default(CancellationTokenRegistration); HttpStatusCode statusCode = HttpStatusCode.OK; Uri connectionUri = null; try { cancelRegistration = cancellationToken.Register(() => { DisconnectAsync(httpConnection).ContinueWith(t => { if (t.Exception != null) { Logger.Log(LogLevel.Info, LOG_APP, $"Disconnection exception: {t.Exception}"); } }, TaskScheduler.Default); }, useSynchronizationContext: false); if (httpConnection.DoOutput) { using (var stream = await request.Content.ReadAsStreamAsync().ConfigureAwait(false)) { await stream.CopyToAsync(httpConnection.OutputStream, 4096, cancellationToken) .ConfigureAwait(false); } } statusCode = await Task.Run(() => (HttpStatusCode)httpConnection.ResponseCode).ConfigureAwait(false); connectionUri = new Uri(httpConnection.URL.ToString()); } finally { cancelRegistration.Dispose(); } if (cancellationToken.IsCancellationRequested) { await DisconnectAsync(httpConnection).ConfigureAwait(continueOnCapturedContext: false); cancellationToken.ThrowIfCancellationRequested(); } // If the request was redirected we need to put the new URL in the request request.RequestUri = connectionUri; var ret = new AndroidHttpResponseMessage(javaUrl, httpConnection) { RequestMessage = request, ReasonPhrase = httpConnection.ResponseMessage, StatusCode = statusCode, }; if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"Status code: {statusCode}"); } bool disposeRet; if (HandleRedirect(statusCode, httpConnection, redirectState, out disposeRet)) { if (disposeRet) { ret.Dispose(); ret = null; } return(ret); } switch (statusCode) { case HttpStatusCode.Unauthorized: case 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 return the body of the response too, but the Java client will throw // a FileNotFound exception if we attempt to access the input stream. // Instead we try to read the error stream and return an default message if the error stream isn't readable. ret.Content = GetErrorContent(httpConnection, 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..."); } ret.Content = GetContent(httpConnection, httpConnection.InputStream); } else { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"Status code is {statusCode}, reading..."); } // For 400 >= response code <= 599 the Java client throws the FileNotFound exception when attempting to read from the input stream. // Instead we try to read the error stream and return an empty string if the error stream isn't readable. ret.Content = GetErrorContent(httpConnection, 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); }
protected override string RunInBackground(params Dictionary <string, string>[] @params) { HttpURLConnection uRLConnection = null; try { URL uRL = new URL(URL_STRING); uRLConnection = (HttpURLConnection)uRL.OpenConnection(); uRLConnection.ConnectTimeout = 15000; uRLConnection.ReadTimeout = 15000; var responseCode = uRLConnection.ResponseCode; if (responseCode == HttpStatus.Ok) { Java.Lang.StringBuilder stringBuilder = new Java.Lang.StringBuilder(); using (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(uRLConnection.InputStream))) { string line; while ((line = bufferedReader.ReadLine()) != null) { stringBuilder.Append(line); } } JObject jsonResponse = JObject.Parse(stringBuilder.ToString()); string chatUrl = jsonResponse[JSON_CHAT_URL].ToString(); chatUrl = chatUrl.Replace(PLACEHOLDER_LICENCE, @params[0].GetValueOrDefault(ChatWindowFragment.KEY_LICENCE_NUMBER)); chatUrl = chatUrl.Replace(PLACEHOLDER_GROUP, @params[0].GetValueOrDefault(ChatWindowFragment.KEY_GROUP_ID)); chatUrl += "&native_platform=android"; if (@params[0].GetValueOrDefault(ChatWindowFragment.KEY_VISITOR_NAME) != null) { chatUrl += $"&name={URLEncoder.Encode(@params[0].GetValueOrDefault(ChatWindowFragment.KEY_VISITOR_NAME), "UTF-8").Replace("+", "%20")}"; } if (@params[0].GetValueOrDefault(ChatWindowFragment.KEY_VISITOR_EMAIL) != null) { chatUrl += $"&email={URLEncoder.Encode(@params[0].GetValueOrDefault(ChatWindowFragment.KEY_VISITOR_EMAIL), "UTF-8")}"; } string customParams = EscapeCustomParams(@params[0], chatUrl); if (!TextUtils.IsEmpty(customParams)) { chatUrl += $"¶ms={customParams}"; } if (!chatUrl.StartsWith("http")) { chatUrl = $"https://{chatUrl}"; } return(chatUrl); } } catch (MalformedURLException e) { e.PrintStackTrace(); } catch (IOException e) { e.PrintStackTrace(); } catch (JSONException e) { e.PrintStackTrace(); } catch (SecurityException e) { Log.Error("LiveChat Widget", "Missing internet permission!"); e.PrintStackTrace(); } finally { if (uRLConnection != null) { try { uRLConnection.Disconnect(); } catch (Java.Lang.Exception ex) { ex.PrintStackTrace(); } } } return(null); }
bool HandleRedirect(HttpStatusCode redirectCode, HttpURLConnection httpConnection, RequestRedirectionState redirectState, out bool disposeRet) { if (!AllowAutoRedirect) { disposeRet = false; return(true); // We shouldn't follow and there's no data to fetch, just return } disposeRet = true; redirectState.NewUrl = null; switch (redirectCode) { case HttpStatusCode.MultipleChoices: // 300 break; case HttpStatusCode.Moved: // 301 case HttpStatusCode.Redirect: // 302 case HttpStatusCode.SeeOther: // 303 redirectState.Method = HttpMethod.Get; break; case HttpStatusCode.TemporaryRedirect: // 307 break; default: if ((int)redirectCode >= 300 && (int)redirectCode < 400) { throw new InvalidOperationException($"HTTP Redirection status code {redirectCode} ({(int)redirectCode}) not supported"); } return(false); } IDictionary <string, IList <string> > headers = httpConnection.HeaderFields; IList <string> locationHeader; if (!headers.TryGetValue("Location", out locationHeader) || locationHeader == null || locationHeader.Count == 0) { throw new InvalidOperationException($"HTTP connection redirected with code {redirectCode} ({(int)redirectCode}) but no Location header found in response"); } if (locationHeader.Count > 1 && Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"More than one location header for HTTP {redirectCode} redirect. Will use the first one."); } redirectState.RedirectCounter++; if (redirectState.RedirectCounter >= MaxAutomaticRedirections) { throw new WebException($"Maximum automatic redirections exceeded (allowed {MaxAutomaticRedirections}, redirected {redirectState.RedirectCounter} times)"); } string redirectUrl = locationHeader [0]; string protocol = httpConnection.URL?.Protocol; if (redirectUrl.StartsWith("//", StringComparison.Ordinal)) { // When redirecting to an URL without protocol, we use the protocol of previous request // See https://tools.ietf.org/html/rfc3986#section-5 (example in section 5.4) redirectUrl = protocol + ":" + redirectUrl; } redirectState.NewUrl = new Uri(redirectUrl, UriKind.Absolute); if (Logger.LogNet) { Logger.Log(LogLevel.Debug, LOG_APP, $"Request redirected to {redirectState.NewUrl}"); } return(true); }
Task <HttpResponseMessage> ProcessRequest(HttpRequestMessage request, URL javaUrl, HttpURLConnection httpConnection, CancellationToken cancellationToken, RequestRedirectionState redirectState) { cancellationToken.ThrowIfCancellationRequested(); httpConnection.InstanceFollowRedirects = false; // We handle it ourselves RequestedAuthentication = null; ProxyAuthenticationRequested = false; return(DoProcessRequest(request, javaUrl, httpConnection, cancellationToken, redirectState)); }
/// <exception cref="System.IO.IOException"/> public HttpURLConnection Configure(HttpURLConnection conn) { return(conn); }