public WebConnectionStream(WebConnection cnc, WebConnectionData data) { if (data == null) throw new InvalidOperationException("data was not initialized"); if (data.Headers == null) throw new InvalidOperationException("data.Headers was not initialized"); if (data.Request == null) throw new InvalidOperationException("data.request was not initialized"); _isRead = true; _pending = new ManualResetEvent(true); _request = data.Request; _readTimeout = _request.ReadWriteTimeout; _writeTimeout = _readTimeout; _cnc = cnc; var contentType = data.Headers["Transfer-Encoding"]; var chunkedRead = (contentType != null && contentType.IndexOf("chunked", StringComparison.OrdinalIgnoreCase) != -1); var clength = data.Headers["Content-Length"]; // Negative numbers? if (!long.TryParse(clength, out _streamLength)) _streamLength = -1; if (!chunkedRead && _streamLength >= 0) { _contentLength = _streamLength; if (_contentLength == 0 && !IsNtlmAuth()) ReadAllAsync().Wait(); // TODO: Don't block. } else _contentLength = long.MaxValue; }
/** * @note event fired when login button is clicked **/ private void btnLogin_Click(object sender, EventArgs e) { /** * @note perform login check and open main window. **/ string username = txtUsername.Text, password = txtPassword.Text; lbLoginBanner.Text = ""; /** * @note form validation **/ if (username.Length <= 2 || password.Length <= 6) { lbLoginBanner.Text = "Please Complete the Form!"; } else { try { WebConnection webRequest = new WebConnection("http://ontrackapp.org/ajax/remotelogin", "POST", "username="******"&password="******"Login Failed. Please Try Again!"; } } catch (WebException) { lbLoginBanner.Text = "Please Check Your Connection"; } } }
internal bool WriteRequestAsync(SimpleAsyncResult result) { if (requestWritten) { return(false); } requestWritten = true; if (sendChunked || !allowBuffering || writeBuffer == null) { return(false); } // Keep the call for a potential side-effect of GetBuffer var bytes = writeBuffer.GetBuffer(); var length = (int)writeBuffer.Length; if (request.ContentLength != -1 && request.ContentLength < length) { nextReadCalled = true; cnc.Close(true); throw new WebException("Specified Content-Length is less than the number of bytes to write", null, WebExceptionStatus.ServerProtocolViolation, null); } SetHeadersAsync(true, inner => { if (inner.GotException) { result.SetCompleted(inner.CompletedSynchronously, inner.Exception); return; } if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100) { result.SetCompleted(inner.CompletedSynchronously); return; } if (!initRead) { initRead = true; WebConnection.InitRead(cnc); } if (length == 0) { complete_request_written = true; result.SetCompleted(inner.CompletedSynchronously); return; } cnc.BeginWrite(request, bytes, 0, length, r => { try { complete_request_written = cnc.EndWrite(request, false, r); result.SetCompleted(false); } catch (Exception exc) { result.SetCompleted(false, exc); } }, null); }); return(true); }
private async void BTNsend_Click(object sender, RoutedEventArgs e) { PRGRSLFsend.ProgressStart(); String name = name_box.Text; if ("".Equals(name)) { Constants.BoxPage.ShowMessage("物品名字不能为空"); return; } String phone = phone_box.Text; if ("".Equals(phone)) { Constants.BoxPage.ShowMessage("电话号码不能为空"); return; } String detail = detail_box.Text; String type = "other"; switch (type_box.SelectedIndex) { case 0: { type = "card"; } break; case 1: { type = "book"; } break; case 2: { type = "device"; } break; case 3: { type = "other"; } break; default: break; } String lost_or_found = "lost"; switch (lost_or_found_box.SelectedIndex) { case 0: { lost_or_found = "lost"; } break; case 1: { lost_or_found = "found"; } break; default: break; } String action_time_str = ((Util.GetTimeStamp(action_date_chooser.Date.Date) + action_time_chooser.Time.Milliseconds) / 1000).ToString(); List <Parameters> param = new List <Parameters>(); param.Add(new Parameters("name", name)); param.Add(new Parameters("type", type)); param.Add(new Parameters("detail", detail)); param.Add(new Parameters("action_time", action_time_str)); param.Add(new Parameters("poster_phone", phone)); param.Add(new Parameters("lost_or_found", lost_or_found)); param.Add(new Parameters("token", Constants.token)); String img_str = null; if (file != null) { var a = await file.OpenAsync(FileAccessMode.ReadWrite); Stream stream = a.AsStream(); byte[] bts = Util.StreamToBytes(stream); img_str = Convert.ToBase64String(bts); param.Add(new Parameters("imgData", img_str)); } Parameters result = await WebConnection.connect(Constants.domain + "/services/LFpost.php", param); PRGRSLFsend.ProgressEnd(); try { if (result.name != "200") { Util.DealWithDisconnect(result); return; } JsonObject jsonObject = JsonObject.Parse(result.value); int success = (int)jsonObject.GetNamedNumber("success"); if (success == 0) { Constants.BoxPage.ShowMessage(jsonObject.GetNamedString("reason", "nothing to know")); return; } return; } catch (Exception) { return; } }
public WebConnectionStream(WebConnection cnc, HttpWebRequest request) { _readTimeout = request.ReadWriteTimeout; _writeTimeout = _readTimeout; _isRead = false; _cnc = cnc; _request = request; _allowBuffering = request.InternalAllowBuffering; _sendChunked = request.SendChunked; if (_sendChunked) _pending = new ManualResetEvent(true); else if (_allowBuffering) _writeBuffer = new MemoryStream(); }
public ConnectionState (WebConnectionGroup group) { Group = group; idleSince = DateTime.UtcNow; Connection = new WebConnection (this, group.sPoint); }
public void TestDownloadPageContent(string url, string expOutput) { var content = new WebConnection().DownloadPageContent(url); Assert.AreEqual(content, expOutput); }
public async Task ConnectAsync(Uri uri, CancellationToken cancellationToken) { state = WebSocketState.Connecting; var httpUri = new UriBuilder(uri); if (uri.Scheme == "wss") { httpUri.Scheme = "https"; } else { httpUri.Scheme = "http"; } req = (HttpWebRequest)WebRequest.Create(httpUri.Uri); req.ReuseConnection = true; if (options.Cookies != null) { req.CookieContainer = options.Cookies; } if (options.CustomRequestHeaders.Count > 0) { foreach (var header in options.CustomRequestHeaders) { req.Headers[header.Key] = header.Value; } } var secKey = Convert.ToBase64String(Encoding.ASCII.GetBytes(Guid.NewGuid().ToString().Substring(0, 16))); string expectedAccept = Convert.ToBase64String(SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(secKey + Magic))); req.Headers["Upgrade"] = "WebSocket"; req.Headers["Sec-WebSocket-Version"] = VersionTag; req.Headers["Sec-WebSocket-Key"] = secKey; req.Headers["Sec-WebSocket-Origin"] = uri.Host; if (options.SubProtocols.Count > 0) { req.Headers["Sec-WebSocket-Protocol"] = string.Join(",", options.SubProtocols); } if (options.Credentials != null) { req.Credentials = options.Credentials; } if (options.ClientCertificates != null) { req.ClientCertificates = options.ClientCertificates; } if (options.Proxy != null) { req.Proxy = options.Proxy; } req.UseDefaultCredentials = options.UseDefaultCredentials; req.Connection = "Upgrade"; HttpWebResponse resp = null; try { resp = (HttpWebResponse)(await req.GetResponseAsync().ConfigureAwait(false)); } catch (Exception e) { throw new WebSocketException(WebSocketError.Success, e); } connection = req.StoredConnection; underlyingSocket = connection.socket; if (resp.StatusCode != HttpStatusCode.SwitchingProtocols) { throw new WebSocketException("The server returned status code '" + (int)resp.StatusCode + "' when status code '101' was expected"); } if (!string.Equals(resp.Headers["Upgrade"], "WebSocket", StringComparison.OrdinalIgnoreCase) || !string.Equals(resp.Headers["Connection"], "Upgrade", StringComparison.OrdinalIgnoreCase) || !string.Equals(resp.Headers["Sec-WebSocket-Accept"], expectedAccept)) { throw new WebSocketException("HTTP header error during handshake"); } if (resp.Headers["Sec-WebSocket-Protocol"] != null) { if (!options.SubProtocols.Contains(resp.Headers["Sec-WebSocket-Protocol"])) { throw new WebSocketException(WebSocketError.UnsupportedProtocol); } subProtocol = resp.Headers["Sec-WebSocket-Protocol"]; } state = WebSocketState.Open; }
/// <summary> /// Construct the WebServer /// </summary> internal WebServer() { string startIn = Assembly.GetExecutingAssembly().Location; startIn = startIn.Substring(0, startIn.LastIndexOf('\\')); Directory.SetCurrentDirectory(startIn); LoadConfiguration(); try { theListener = new TcpListener(IPAddress.Any, listenPort); Console.WriteLine("Server started on " + theListener.LocalEndpoint); theListener.Start(); startTime = DateTime.Now; webConn = new WebConnection(); listenThread = new Thread(new ThreadStart(Listen)); listenThread.Start(); } catch (SocketException) { Console.WriteLine("Socket Exception: Please change the listen port."); } }
private async void DoConnection(IPGW_type connectType, String hintString) { String type = "connect"; String free = "2"; if (connectType == IPGW_type.ConnectNofree) { free = "1"; } else if (connectType == IPGW_type.Disconnect) { type = "disconnect"; } else if (connectType == IPGW_type.DisconnectAll) { type = "disconnectall"; } //if (!Constants.isLogin()) ;//日后加入登录内容 List <Parameters> paramList = new List <Parameters>(); /** * 这两句仅用于测试!!! * 必须改掉! */ //Constants.username = "******"; //Constants.password = "******"; paramList.Add(new Parameters("uid", Constants.username)); paramList.Add(new Parameters("password", Constants.password)); paramList.Add(new Parameters("operation", type)); paramList.Add(new Parameters("range", free)); paramList.Add(new Parameters("timeout", "-1")); Reset(); PageStatus = IPGWstatus.Connecting; STRBDconnectEnd.Begin(); Parameters parameter = await WebConnection.Connect("https://its.pku.edu.cn:5428/ipgatewayofpku", paramList); if (!"200".Equals(parameter.name)) { if ("-1".Equals(parameter.name)) { Constants.BoxPage.ShowMessage("无法连接网络"); } else { Constants.BoxPage.ShowMessage("无法连接到服务器 (HTTP " + parameter.name + ")"); } } else { Dictionary <String, String> map = GetReturnMsg(parameter.value); if (!map.ContainsKey("SUCCESS")) { Constants.BoxPage.ShowMessage("网关连接失败,请重试"); STRBDconnecting.Stop(); return; } String successMsg = map["SUCCESS"]; Boolean success = "YES".Equals(successMsg); if (connectType == IPGW_type.ConnectFree || connectType == IPGW_type.ConnectNofree) { if (success) { String scope = ""; if ("f".Equals(map["SCOPE"].Trim())) { scope = "免费地址"; } else if ("international".Equals(map["SCOPE"].Trim())) { scope = "收费地址"; } hintString = scope + "\r\n" + "IP: " + map["IP"] + "\r\n当前连接数:" + map["CONNECTIONS"] + "\r\n" + "已用时长: " + map["FR_TIME"] + "\r\n" + "账户余额:" + map["BALANCE"]; if (free.Equals("1")) { Boolean whether_get_bing = false; String his_str = Editor.getString("bing_history", ""); try { if (!his_str.Equals("")) { DateTime history = DateTime.Parse(his_str); int span = DateTime.Now.Day - history.Day; if (span >= 1 || span < 0) { whether_get_bing = true; } } else { whether_get_bing = true; } } catch { } if (whether_get_bing) { await GetBingToday(); } } // 显示对话框 //两个Lib的函数?仍然没看懂 Constants.BoxPage.ShowMessage(hintString, "连接状态:已连接"); } else { Constants.BoxPage.ShowMessage(map["REASON"], "连接失败"); //一个Lib的函数,未实现 } STRBDconnecting.Stop(); return; } if (connectType == IPGW_type.Disconnect) { if (success) { Constants.BoxPage.ShowMessage("", "断开连接成功"); } else { Constants.BoxPage.ShowMessage(map["REASON"], "断开连接失败"); STRBDconnecting.Stop(); return; } } if (connectType == IPGW_type.DisconnectAll) { if (success) { Constants.BoxPage.ShowMessage("", "断开全部连接成功"); } else { Constants.BoxPage.ShowMessage(map["REASON"], "断开全部连接失败"); STRBDconnecting.Stop(); return; } } } }
internal async Task <Stream> CreateStream(WebConnectionTunnel tunnel, CancellationToken cancellationToken) { #if SECURITY_DEP var socket = networkStream.InternalSocket; WebConnection.Debug($"MONO TLS STREAM CREATE STREAM: {socket.ID}"); sslStream = new SslStream(networkStream, false, provider, settings); try { var host = request.Host; if (!string.IsNullOrEmpty(host)) { var pos = host.IndexOf(':'); if (pos > 0) { host = host.Substring(0, pos); } } await sslStream.AuthenticateAsClientAsync( host, request.ClientCertificates, (SslProtocols)ServicePointManager.SecurityProtocol, ServicePointManager.CheckCertificateRevocationList).ConfigureAwait(false); status = WebExceptionStatus.Success; request.ServicePoint.UpdateClientCertificate(sslStream.LocalCertificate); } catch (Exception ex) { WebConnection.Debug($"MONO TLS STREAM ERROR: {socket.ID} {socket.CleanedUp} {ex.Message}"); if (socket.CleanedUp) { status = WebExceptionStatus.RequestCanceled; } else if (CertificateValidationFailed) { status = WebExceptionStatus.TrustFailure; } else { status = WebExceptionStatus.SecureChannelFailure; } request.ServicePoint.UpdateClientCertificate(null); CloseSslStream(); throw; } try { if (tunnel?.Data != null) { await sslStream.WriteAsync(tunnel.Data, 0, tunnel.Data.Length, cancellationToken).ConfigureAwait(false); } } catch { status = WebExceptionStatus.SendFailure; CloseSslStream(); throw; } return(sslStream); #else throw new PlatformNotSupportedException(EXCEPTION_MESSAGE); #endif }
public PortlessWebConnection(WebHost host) { connection = new InternalWebConnection(host); }
public override void Close() { if (GetResponseOnClose) { if (disposed) { return; } disposed = true; var response = (HttpWebResponse)request.GetResponse(); response.ReadAll(); response.Close(); return; } if (sendChunked) { if (disposed) { return; } disposed = true; pending.WaitOne(); byte[] chunk = Encoding.ASCII.GetBytes("0\r\n\r\n"); string err_msg = null; cnc.Write(request, chunk, 0, chunk.Length, ref err_msg); return; } if (isRead) { if (!nextReadCalled) { CheckComplete(); // If we have not read all the contents if (!nextReadCalled) { nextReadCalled = true; cnc.Close(true); } } disposed = true; return; } else if (!allowBuffering) { complete_request_written = true; if (!initRead) { initRead = true; WebConnection.InitRead(cnc); } return; } if (disposed || requestWritten) { return; } long length = request.ContentLength; if (!sendChunked && length != -1 && totalWritten != length) { IOException io = new IOException("Cannot close the stream until all bytes are written"); nextReadCalled = true; cnc.Close(true); throw new WebException("Request was cancelled.", io, WebExceptionStatus.RequestCanceled); } // Commented out the next line to fix xamarin bug #1512 //WriteRequest (); disposed = true; }
/// <summary> /// 登出豆瓣账户 /// </summary> public void Logout() { WebConnection.GetCommand(string.Format(@"http://douban.fm/partner/logout?source=radio&ck={0}&no_login=y", result.User.CK)); WebConnection.ClearCookie(); SaveUserInfo(string.Empty); }
public Imgur(WebConnection web) { WebConnection = web; }
/*// <summary> /// The number of busy connections /// </summary> private Wrapped<ulong> NumBusyConnections = 0;*/ /// <summary> /// Called when the header is completely loaded /// </summary> /// <param name="socketReader"></param> protected void PerformRequest() { //Thread = Thread.CurrentThread; /*using (TimedLock.Lock(NumBusyConnections)) NumBusyConnections.Value++;*/ if (!WebServer.KeepAlive || !Socket.Connected || !WebServer.Running) KeepAlive = false; else if (!WebConnection.Headers.ContainsKey("CONNECTION")) KeepAlive = false; else if ("keep-alive" != WebConnection.Headers["CONNECTION"].ToLower()) KeepAlive = false; else KeepAlive = true; // (I think) this ensures that the web connection is garbage collected // I forget why I did this, but it seems that there shouldn't be a reference to the webconnection while the request is being handled WebConnection webConnection = WebConnection; WebConnection = null; Busy.BlockWhileBusy(); WebServer.RequestDelegateQueue.QueueUserWorkItem(delegate(object state) { webConnection.HandleConnection((IWebConnectionContent)state); }, Content); }
/// <summary> /// Overall driver for watching the socket. This is started on its own thread /// </summary> public void MonitorSocket() { try { // Timeout if the client takes a really long time to send bytes Socket.ReceiveTimeout = Convert.ToInt32(TimeSpan.FromSeconds(15).TotalMilliseconds); WebConnection = new WebConnection(WebServer, Socket.RemoteEndPoint, SendToBrowser); ReadHeader(); } catch (ThreadAbortException) { Close(); } // Exceptions that occur when a socket is closed are just swallowed; this keeps the logs clean catch (ObjectDisposedException) { WebConnectionIOState = WebConnectionIOState.Disconnected; Close(); } catch (SocketException)// se) { //log.InfoFormat("Error when performing IO for a connection from {0}", se, RemoteEndPoint); WebConnectionIOState = WebConnectionIOState.Disconnected; Close(); } catch (Exception e) { log.ErrorFormat("Fatal error when performing IO for a connection from {0}", e, RemoteEndPoint); WebConnectionIOState = WebConnectionIOState.Disconnected; Close(); } }
private async void LSTVWinfo_ItemClick(object sender, ItemClickEventArgs e) { switch ((e.ClickedItem as UsualItemData).ID) { case 0: { FRAMEdetail.Navigate(typeof(ImageShowPage), new Parameters("北大地图", "ms-appx:///Assets/pkumap.jpg")); if (VSGinfo.CurrentState == narrow) { UpdateVisualState(narrow, null); } } break; case 1: { FRAMEdetail.Navigate(typeof(ImageShowPage), new Parameters("北京地铁图", "ms-appx:///Assets/subwaymap.jpg")); if (VSGinfo.CurrentState == narrow) { UpdateVisualState(narrow, null); } } break; case 2: { PRGRSinfo.ProgressStart(); await InfoUtil.GetCardAmount(); PRGRSinfo.ProgressEnd(); } break; case 3: { first : BitmapImage bmp = new BitmapImage(); Stream stream = await WebConnection.Connect_for_stream("http://dean.pku.edu.cn/student/yanzheng.php?act=init"); if (stream == null) { Constants.BoxPage.ShowMessage("获取验证码失败!"); return; } var ran_stream = await Util.StreamToRandomAccessStream(stream); bmp.SetSource(ran_stream); IMGverify.Source = bmp; if (DLGshowing) { return; } ContentDialogResult res = await DLGverify.ShowAsync(); if (res == ContentDialogResult.Primary) { String phpsessid = await Dean.get_session_id(verifyCode); if (phpsessid == "") { goto first; } PRGRSinfo.ProgressStart(); Parameters parameters = await WebConnection.Connect(Constants.domain + "/services/pkuhelper/allGrade.php?phpsessid=" + phpsessid, null); if (parameters.name != "200") { Util.DealWithDisconnect(parameters); PRGRSinfo.ProgressEnd(); } else { PRGRSinfo.ProgressEnd(); FRAMEdetail.Navigate(typeof(GradePage), parameters.value); if (VSGinfo.CurrentState == narrow) { UpdateVisualState(narrow, null); } } } } break; case 4: { FRAMEdetail.Navigate(typeof(SchoolCalendarPage)); if (VSGinfo.CurrentState == narrow) { UpdateVisualState(narrow, null); } } break; case 5: { FRAMEdetail.Navigate(typeof(PhoneList)); if (VSGinfo.CurrentState == narrow) { UpdateVisualState(narrow, null); } } break; } }
public static async Task <IPGWMsg> DoConnection(IPGW_type connectType, String hintString = "") { if (connectType == IPGW_type.None) { return(null); } String type = "connect"; String free = "2"; if (connectType == IPGW_type.ConnectNofree) { free = "1"; } else if (connectType == IPGW_type.Disconnect) { type = "disconnect"; } else if (connectType == IPGW_type.DisconnectAll) { type = "disconnectall"; } List <Parameters> paramList = new List <Parameters>(); paramList.Add(new Parameters("uid", Constants.username)); paramList.Add(new Parameters("password", Constants.password)); paramList.Add(new Parameters("operation", type)); paramList.Add(new Parameters("range", free)); paramList.Add(new Parameters("timeout", "-1")); Parameters result = await WebConnection.Connect("https://its.pku.edu.cn:5428/ipgatewayofpku", paramList); if (!"200".Equals(result.name)) { Util.DealWithDisconnect(result); return(null); } Dictionary <String, String> map = GetReturnMsg(result.value); if (!map.ContainsKey("SUCCESS")) { return(null); } String successMsg = map["SUCCESS"]; bool success = "YES".Equals(successMsg); String title = "", content = ""; switch (connectType) { case IPGW_type.ConnectFree: { if (success) { title = "连接免费地址成功"; } else { title = map["REASON"]; } String scope = ""; if ("f".Equals(map["SCOPE"].Trim())) { scope = "免费地址"; } else if ("international".Equals(map["SCOPE"].Trim())) { scope = "收费地址"; } content = scope + "\n" + "IP: " + map["IP"] + "\n当前连接数:" + map["CONNECTIONS"] + "\n" + "已用时长: " + map["FR_TIME"] + "\n" + "账户余额:" + map["BALANCE"]; } break; case IPGW_type.ConnectNofree: { if (success) { title = "连接收费地址成功"; } else { title = map["REASON"]; } String scope = ""; if ("f".Equals(map["SCOPE"].Trim())) { scope = "免费地址"; } else if ("international".Equals(map["SCOPE"].Trim())) { scope = "收费地址"; } content = scope + "\n" + "IP: " + map["IP"] + "\n当前连接数:" + map["CONNECTIONS"] + "\n" + "已用时长: " + map["FR_TIME"] + "\n" + "账户余额:" + map["BALANCE"]; /*if (free.Equals("1")) * { * Boolean whether_get_bing = false; * String his_str = Editor.getString("bing_history", ""); * try * { * if (!his_str.Equals("")) * { * DateTime history = DateTime.Parse(his_str); * int span = DateTime.Now.Day - history.Day; * if (span >= 1 || span < 0) whether_get_bing = true; * } * else whether_get_bing = true; * } * catch { } * if (whether_get_bing) * { * await GetBingToday(); * } * }*/ } break; case IPGW_type.Disconnect: { if (success) { title = "断开连接成功"; } else { title = "断开连接失败"; content = map["REASON"]; } } break; case IPGW_type.DisconnectAll: { if (success) { title = "断开全部连接成功"; } else { title = "断开全部连接失败"; content = map["REASON"]; } } break; } return(new IPGWMsg(success, title, content, connectType)); }
internal User(uint Id, WebConnection Connection, string Name) { UserId = Id; Socket = Connection; Username = Name; }
public Cleverbot(WebConnection webconnection) { WebConnection = webconnection; Conversation = ""; }
public ConnectionState(WebConnectionGroup group) { Group = group; idleSince = DateTime.UtcNow; Connection = new WebConnection(this, group.sPoint); }
private async Task <Parameters> ExecuteConnect() { try { Parameters parameters = await WebConnection.Connect(Constants.domain + "/services/login/local.php", null); if (!"200".Equals(parameters.name)) { return(parameters); } JsonObject jsonObject = JsonObject.Parse(parameters.value); int code = (int)jsonObject.GetNamedNumber("code"); if (code != 0) { return(parameters); } Boolean local = (jsonObject.GetNamedNumber("local", 0) != 0); String token = ""; /*JsonObject jsonObject; * Boolean local = true; * Parameters parameters; * String token = "";*/ if (local) { await WebConnection.Connect("https://portal.pku.edu.cn/portal2013/index.jsp", null); List <Parameters> list1 = new List <Parameters>(); list1.Add(new Parameters("appid", "portal")); list1.Add(new Parameters("userName", Username)); list1.Add(new Parameters("password", Password)); list1.Add(new Parameters("redirUrl", "http://portal.pku.edu.cn/portal2013/login.jsp/../ssoLogin.do")); parameters = await WebConnection.Connect("https://iaaa.pku.edu.cn/iaaa/oauthlogin.do", list1); if (!"200".Equals(parameters.name)) { return(parameters); } jsonObject = JsonObject.Parse(parameters.value); Boolean success = jsonObject.GetNamedBoolean("success"); if (!success) { JsonObject errors = jsonObject.GetNamedObject("errors"); String msg = errors.GetNamedString("msg", "登录失败"); return(new Parameters("200", "{\"code\": 1, \"msg\": \"" + msg + "\"}")); } token = jsonObject.GetNamedString("token"); Random ra = new Random(); Parameters tempLoginPara = await WebConnection.Connect("http://portal.pku.edu.cn/portal2013/ssoLogin.do?rand=" + ra.NextDouble() + "&token=" + token, null); tempLoginPara = await WebConnection.Connect("http://portal.pku.edu.cn/portal2013/isUserLogged.do", null); //username = ""; //password = ""; } List <Parameters> list = new List <Parameters>(); list.Add(new Parameters("uid", Username)); list.Add(new Parameters("password", Password)); list.Add(new Parameters("token", token)); list.Add(new Parameters("platform", "Android")); return(await WebConnection.Connect(Constants.domain + "/services/login/login.php", list)); } catch (Exception e) { Debug.WriteLine(e.StackTrace); return(new Parameters("200", "{\"code\": 1, \"msg\": \"登录失败,请重试\"}")); } }
public WeatherUnderground(WebConnection webconnection) { WebConnection = webconnection; }
internal void Close() { if (listenThread != null) { listenThread.Abort(); listenThread = null; } if (webConn != null) { webConn.Close(); webConn = null; } if (theListener != null) { theListener.Stop(); theListener = null; } }
private async Task <List <LostFoundInfo> > execute_load_more() { String type_str = "", token = ""; switch (type) { case LFstatus.Lost: { type_str = "lost"; } break; case LFstatus.Found: { type_str = "found"; } break; case LFstatus.My: { token = Constants.token; } break; default: break; } Parameters result = await WebConnection.Connect(Constants.domain + "/services/LFList.php?type=" + type_str + "&page=" + (current_page).ToString() + "&token=" + token, new List <Parameters>()); if (result.name != "200") { return(null); } JsonObject json; JsonArray data; try { json = JsonObject.Parse(result.value); data = json.GetNamedArray("data"); } catch (Exception) { return(null); } List <LostFoundInfo> more_infos = new List <LostFoundInfo>(); if (type != LFstatus.My) { try { Boolean bmore = json.GetNamedBoolean("more"); if (!bmore) { has_more_items = false; } } catch (Exception) { } } foreach (var info in data) { try { JsonObject data_obj = info.GetObject(); int tid = int.Parse(data_obj.GetNamedString("id")); if (type == LFstatus.My) { foreach (var temp in this) { if (temp.id == tid) { HasMoreItems = false; return(null); } } } String tname = data_obj.GetNamedString("name"); String tlost_or_found = data_obj.GetNamedString("lost_or_found"); String ttypr = data_obj.GetNamedString("type"); String tdetail = data_obj.GetNamedString("detail"); long tpost_time = long.Parse(data_obj.GetNamedString("post_time")); long taction_time = long.Parse(data_obj.GetNamedString("action_time")); String timage = data_obj.GetNamedString("image"); String tposter_uid = data_obj.GetNamedString("poster_uid"); String tposter_phone = data_obj.GetNamedString("poster_phone"); String tposter_name = data_obj.GetNamedString("poster_name"); String tposter_college = data_obj.GetNamedString("poster_college"); LostFoundInfo temp_info = new LostFoundInfo(tid, tname, tlost_or_found, ttypr, tdetail, tpost_time, taction_time, timage, tposter_uid, tposter_phone , tposter_name, tposter_college); if (type == LFstatus.My) { temp_info.mine = true; } more_infos.Add(temp_info); } catch { } } return(more_infos); }
static void PrepareSharingNtlm (WebConnection cnc, HttpWebRequest request) { if (!cnc.NtlmAuthenticated) return; bool needs_reset = false; NetworkCredential cnc_cred = cnc.NtlmCredential; bool isProxy = (request.Proxy != null && !request.Proxy.IsBypassed (request.RequestUri)); ICredentials req_icreds = (!isProxy) ? request.Credentials : request.Proxy.Credentials; NetworkCredential req_cred = (req_icreds != null) ? req_icreds.GetCredential (request.RequestUri, "NTLM") : null; if (cnc_cred == null || req_cred == null || cnc_cred.Domain != req_cred.Domain || cnc_cred.UserName != req_cred.UserName || cnc_cred.Password != req_cred.Password) { needs_reset = true; } if (!needs_reset) { bool req_sharing = request.UnsafeAuthenticatedConnectionSharing; bool cnc_sharing = cnc.UnsafeAuthenticatedConnectionSharing; needs_reset = (req_sharing == false || req_sharing != cnc_sharing); } if (needs_reset) { cnc.Close (false); // closes the authenticated connection cnc.ResetNtlm (); } }
private async Task <List <NoticeInfo> > execute_load_more() { String url = Constants.domain + "/pkuhelper/nc/fetch.php?token=" + Constants.token; url = url + "&p=" + (current_page + 1).ToString() + "&platform=Android"; if (type == ONE) { url = url + "&sid=" + sid.ToString(); } Parameters param = await WebConnection.Connect(url, new List <Parameters>()); if (param.name != "200") { return(null); } else { try { JsonObject jsonObject = JsonObject.Parse(param.value); int code = (int)jsonObject.GetNamedNumber("code"); if (code == 1) { Constants.BoxPage.ShowMessage("您还没有设置订阅源!请设置订阅源"); return(null); } JsonArray array = jsonObject.GetNamedArray("data"); List <NoticeInfo> more_infos = new List <NoticeInfo>(); foreach (var info in array) { JsonObject obj = info.GetObject(); String tTitle = obj.GetNamedString("title"); int tnid = int.Parse(obj.GetNamedString("nid")); String turl = obj.GetNamedString("url"); int tsid = int.Parse(obj.GetNamedString("sid")); String tsubscribe = obj.GetNamedString("subscribe"); long ttime = long.Parse(obj.GetNamedString("time")); NoticeInfo temp_info = new NoticeInfo(tnid, tTitle, tsid, turl, tsubscribe, ttime); if (NcSourceQuery.nc_sources != null) { try { NcSourceInfo temp_source; if (NcSourceQuery.nc_sources.TryGetValue(tsid.ToString(), out temp_source)) { temp_info.SourceIcon = temp_source.Icon; temp_info.SourceName = temp_source.Name; } else { temp_info.SourceIcon = null; temp_info.SourceName = "Unknown source name"; } } catch (Exception e) { Debug.WriteLine(e.StackTrace); } } more_infos.Add(temp_info); } return(more_infos); } catch (Exception e) { Debug.WriteLine(e.StackTrace); return(null); } } }