public void HttpRequestHeader_GetKey_Success() { WebHeaderCollection w = new WebHeaderCollection(); w.Add("header1", "value1"); w.Add("header1", "value2"); Assert.NotEmpty(w.GetKey(0)); }
private static async Task GetServerName(string url) { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync(); WebHeaderCollection headers = response.Headers; for (int i = 0; i < headers.Count; i++) { if (headers.GetKey(i).ToLower().Contains("server")) { Console.WriteLine("{0}: {1}", headers.GetKey(i), headers[i]); } } response.Close(); } catch (Exception ex) { Console.WriteLine("Сайт не такой простой нужно подделать заголовок"); } finally { //TODO : add some logic } }
public string get_answer(string txturl) //인터넷에서 소스를 가져와 반환하는 함수 동적 처리에서는 동작하지 않는다.. { HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create(txturl); HttpWebResponse hwrp = (HttpWebResponse)hwr.GetResponse(); WebHeaderCollection whc = hwrp.Headers; string header = null, html = null; for (int i = 0; i < whc.Count; i++) { header += whc.GetKey(i) + " = " + whc.GetKey(i) + "\r\n"; } Stream strm = hwrp.GetResponseStream(); StreamReader sr = new StreamReader(strm, Encoding.UTF8); //Stream strm = hwrp.GetResponseStream(); //StreamReader sr = new StreamReader(strm, Encoding.Default); while (sr.Peek() > -1) { html += sr.ReadLine() + "\r\n"; } sr.Close(); strm.Close(); return(html); }
public byte[] DownloadBytes(string url) { var args = ""; for (int i = 0; i < Headers.Count; i++) { args += "-H '" + Headers.GetKey(i) + ": " + Headers.Get(i) + "' "; } var cc = container.GetCookieHeader(new Uri(url)); if (!string.IsNullOrEmpty(cc)) { args += "-H '" + cc + "'"; } if (args == "-H '") { args = ""; } ProcessStartInfo start = new ProcessStartInfo(); start.FileName = "curl"; start.Arguments = args + url; start.UseShellExecute = false; start.RedirectStandardOutput = true; start.RedirectStandardError = true; start.RedirectStandardInput = false; start.CreateNoWindow = true; Process p = Process.Start(start); p.WaitForExit(); FileStream baseStream = p.StandardOutput.BaseStream as FileStream; byte[] bytes = null; int lastRead = 0; using (MemoryStream ms = new MemoryStream()) { byte[] buffer = new byte[4096]; do { lastRead = baseStream.Read(buffer, 0, buffer.Length); ms.Write(buffer, 0, lastRead); } while (lastRead > 0); bytes = ms.ToArray(); baseStream.Close(); baseStream.Dispose(); } p.WaitForExit(); return(bytes); }
public void GetKey_Fail() { WebHeaderCollection w = new WebHeaderCollection(); w.Add("Accept", "text/plain"); Assert.Throws <ArgumentOutOfRangeException>(() => w.GetKey(-1)); Assert.Throws <ArgumentOutOfRangeException>(() => w.GetKey(42)); }
public void GetKey_Success() { const string key = "Accept"; const string key2 = "Content-Length"; WebHeaderCollection w = new WebHeaderCollection(); w.Add(key, "text/plain"); w.Add(key2, "123"); Assert.Equal(key, w.GetKey(0)); Assert.Equal(key2, w.GetKey(1)); }
/// <summary> /// 获取国家授时中心网提供的时间。(授时中心连接经常出状况,暂时用百度网代替) /// 通过分析网页报头,查找Date对应的值,获得GMT格式的时间。可通过GMT2Local(string gmt)方法转化为本地时间格式。 /// 用法 DateTime netTime = GetNetTime.GMT2Local(GetNetTime.GetNetDate()); /// </summary> /// <returns></returns> public static string GetNetDate() { try { //WebRequest request = WebRequest.Create("http://www.time.ac.cn");//国家授时中心经常连接不上 WebRequest request = WebRequest.Create("http://www.baidu.com"); request.Credentials = CredentialCache.DefaultCredentials; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); WebHeaderCollection myWebHeaderCollection = response.Headers; for (int i = 0; i < myWebHeaderCollection.Count; i++) { string header = myWebHeaderCollection.GetKey(i); string[] values = myWebHeaderCollection.GetValues(header); if (header.Length <= 0 || header == null) { return(null); } else if (header == "Date") { return(values[0]); } } return(null); } catch (Exception ex) { throw ex; } }
void getCookies(WebHeaderCollection headers) { string[] accept = new string[] { "rur", "urlgen", "csrftoken" }; for (int i = 0; i < headers.Count; i++) { string name = headers.GetKey(i); if (name != "Set-Cookie") { continue; } string value = headers.Get(i); foreach (var singleCookie in value.Split(',')) { Match match = Regex.Match(singleCookie, "(.+?)=(.+?);"); if (match.Captures.Count == 0) { continue; } string cname = match.Groups[1].ToString(); string cvalue = match.Groups[2].ToString(); if (accept.Contains(cname) && !string.IsNullOrEmpty(cvalue)) { if (cookies.ContainsKey(cname)) { cookies[cname] = cvalue; } else { cookies.Add(cname, cvalue); } } } } }
public string HeadersAsString() { WebHeaderCollection headers = this.Headers; checked { if (headers != null) { StringBuilder stringBuilder = new StringBuilder(1000); StringBuilder stringBuilder2 = stringBuilder; int arg_26_0 = 0; int num = headers.Count - 1; for (int i = arg_26_0; i <= num; i++) { string key = headers.GetKey(i); string[] values = headers.GetValues(key); stringBuilder2.AppendLine(key); if (values.Length > 0) { int arg_56_0 = 0; int num2 = values.Length - 1; for (int j = arg_56_0; j <= num2; j++) { stringBuilder2.AppendLine(" " + values[j]); } } } return(stringBuilder.ToString()); } return(string.Empty); } }
private void authWithToken() { var myWebClient = new WebClient(); myWebClient.Headers[HttpRequestHeader.ContentType] = "application/json"; myWebClient.Headers.Add("X-Auth-Token", authToken); var data = myWebClient.DownloadString("http://" + ipaddrWithPort + "/identity/v3/auth/projects"); var projects = JsonConvert.DeserializeObject <AllProject>(data); var projectIndex = this.comboBoxProject.SelectedIndex; idProject = projects.projects[projectIndex]; String jsonWithScope = "{\"auth\":{\"identity\":{\"methods\":[\"password\"],\"password\":{\"user\":{\"name\":" + "\"" + this.textBoxUsername.Text + "\",\"domain\":{\"name\":\"Default\"},\"password\":" + "\"" + this.textBoxPassword.Text + "\"}}},\"scope\": {\"project\": {\"id\":" + "\"" + idProject.Id + "\"}}}}"; var responseStringScoped = myWebClient.UploadString("http://" + ipaddrWithPort + "/identity/v3/auth/tokens", jsonWithScope); WebHeaderCollection myWebHeaderCollectionScoped = myWebClient.ResponseHeaders; for (int i = 0; i < myWebHeaderCollectionScoped.Count; i++) { if (myWebHeaderCollectionScoped.GetKey(i) == "X-Subject-Token") { authToken = myWebHeaderCollectionScoped.Get(i); } } authenticated = true; oldSelected = this.comboBoxProject.SelectedIndex; }
/// <summary> /// Gets the metadata or properties. /// </summary> /// <param name="response">The response from server.</param> /// <param name="prefix">The prefix for all the headers.</param> /// <returns>A <see cref="NameValueCollection"/> of the headers with the prefix.</returns> private static NameValueCollection GetMetadataOrProperties(HttpWebResponse response, string prefix) { NameValueCollection nameValues = new NameValueCollection(); int prefixLength = prefix.Length; WebHeaderCollection headers = response.Headers; for (int i = 0; i < headers.Count; i++) { string header = headers.GetKey(i); if (!header.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) { continue; } string[] values = headers.GetValues(header); for (int j = 0; j < values.Length; j++) { nameValues.Add(header.Substring(prefixLength), values[j]); } } return(nameValues); }
private static string GetCookieString(WebHeaderCollection webHeaderCollection) { try { string CokString = ""; for (int i = 0; i < webHeaderCollection.Count; i++) { String header__ = webHeaderCollection.GetKey(i); if (header__ != "Set-Cookie") { continue; } String[] values = webHeaderCollection.GetValues(header__); if (values.Length < 1) { continue; } foreach (string v in values) { if (v != "") { CokString += MrHTTP.StripCokNameANdVal(v) + ";"; } } } if (CokString.Length > 0) { return(CokString.Substring(0, CokString.Length - 1)); } return(CokString); } catch { return(""); } }
public static void GetHeaders(WebRequest request, HttpWebResponse response) { if (response == null || request == null) { return; } string message = (int)response.StatusCode + " " + response.StatusDescription + "\n" + "URL: " + request.RequestUri + "\nMethod type: " + request.Method + "\nRequest data type: " + response.ContentType + "\nHeaders:"; WebHeaderCollection whc = response.Headers; var headers = Enumerable.Range(0, whc.Count) .Select(p => { return(new { Key = whc.GetKey(p), Names = whc.GetValues(p) }); }); foreach (var item in headers) { message += "\n " + item.Key + ":"; foreach (var n in item.Names) { message += " " + n; } } Status = message; }
public FileToDownloadStatusCodes DownloadFile(IFileToDownload myfile) { string str = Path.Combine(this.string_0, myfile.Filename); MyWebClient myWebClient = new MyWebClient(); FileToDownloadStatusCodes downloadStatusCodes = FileToDownloadStatusCodes.OK; try { myWebClient.AllowAutoRedirect = true; myWebClient.DownloadFile(myfile.Url, str); } catch (WebException ex) { HttpWebResponse httpWebResponse = (HttpWebResponse)ex.Response; downloadStatusCodes = httpWebResponse != null ? (FileToDownloadStatusCodes)httpWebResponse.StatusCode : FileToDownloadStatusCodes.UnknownError; } catch (Exception ex) { downloadStatusCodes = FileToDownloadStatusCodes.UnknownError; } if (downloadStatusCodes == FileToDownloadStatusCodes.OK) { if (!System.IO.File.Exists(str)) { return(FileToDownloadStatusCodes.FileNotDownloaded); } try { if (new FileInfo(str).Length < 1L) { downloadStatusCodes = FileToDownloadStatusCodes.FileDownloadedButEmpty; } } catch (Exception ex) { downloadStatusCodes = FileToDownloadStatusCodes.FileUnknownError; } WebHeaderCollection responseHeaders = myWebClient.ResponseHeaders; DateTime creationTime = DateTime.Now; for (int index = 0; index < responseHeaders.Count; ++index) { if (responseHeaders.GetKey(index).Equals("Last-Modified")) { creationTime = DateTime.Parse(responseHeaders.Get(index)); } } try { System.IO.File.SetCreationTime(str, creationTime); } catch (Exception ex) { } } if (myWebClient != null) { myWebClient.Dispose(); } return(downloadStatusCodes); }
public static void Test_WebHeader_02() { string file = @"http\header_01.json"; string file2 = @"http\header_02.json"; file = zPath.Combine(_directory, file); file2 = zPath.Combine(_directory, file2); WebHeaderCollection headers = new WebHeaderCollection(); headers.Add("xxx", "yyy"); headers.Add("xxx", "yyy222"); headers.Add("zzz", "fff"); headers.Add("yyy", "ttt"); for (int i = 0; i < headers.Count; ++i) { string key = headers.GetKey(i); foreach (string value in headers.GetValues(i)) { Trace.WriteLine("{0}: {1}", key, value); } } //headers.zSave(file); BsonDocument doc = headers.ToBsonDocument(); doc.zSave(file); }
public HeaderDictionary(WebHeaderCollection headers) { for (int headerIndex = 0; headerIndex < headers.Count; headerIndex++) { this.Add(headers.GetKey(headerIndex), headers.GetValues(headerIndex).ToList()); } }
public static string GetResponseInfo(WebRequest request, WebResponse response) { // Получаем некоторые данные о сервере string RequestInfo = "Целевой URL: \t" + request.RequestUri + "\nМетод запроса: \t" + request.Method + "\nТип полученных данных: \t" + response.ContentType + "\nДлина ответа: \t" + response.ContentLength + "\nЗаголовки"; // Получаем заголовки, используем LINQ WebHeaderCollection whc = response.Headers; var headers = Enumerable.Range(0, whc.Count) .Select(p => { return(new { Key = whc.GetKey(p), Names = whc.GetValues(p) }); }); foreach (var item in headers) { RequestInfo += "\n " + item.Key + ":"; foreach (var n in item.Names) { RequestInfo += "\t" + n; } } return(RequestInfo); }
public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); WebRequest wrq = WebRequest.Create("http://www.wrox.com"); /* * * HttpWebRequest hwrq = (HttpWebRequest)wrq; * * listBox1.Items.Add("Request Timeout (ms) = " + wrq.Timeout); * listBox1.Items.Add("Request Keep Alive = " + hwrq.KeepAlive); * listBox1.Items.Add("Request AllowAutoRedirect = " + hwrq.AllowAutoRedirect); */ WebResponse wrs = wrq.GetResponse(); WebHeaderCollection whc = wrs.Headers; for (int i = 0; i < whc.Count; i++) { listBox1.Items.Add("Header " + whc.GetKey(i) + " : " + whc[i]); } // // TODO: Add any constructor code after InitializeComponent call // }
//определить сервер private static async Task GetServerName(string url) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync(); WebHeaderCollection headers = response.Headers; for (int i = 0; i < headers.Count; i++) { if (headers.GetKey(i).ToLower().Contains("server")) { Console.WriteLine("{0}: {1}", headers.GetKey(i), headers[i]); } } response.Close(); }
public string Get(string url, WebHeaderCollection headers) { Request = (HttpWebRequest)WebRequest.Create(url); Request.Accept = headers[HttpRequestHeader.Accept]; Request.Connection = headers[HttpRequestHeader.Connection]; Request.KeepAlive = Convert.ToBoolean(headers[HttpRequestHeader.KeepAlive]); Request.Referer = headers[HttpRequestHeader.Referer]; Request.UserAgent = headers[HttpRequestHeader.UserAgent]; var heads = new HttpRequestHeader[] { HttpRequestHeader.Accept, HttpRequestHeader.Connection, HttpRequestHeader.KeepAlive, HttpRequestHeader.Referer, HttpRequestHeader.UserAgent, HttpRequestHeader.ContentLength, HttpRequestHeader.ContentType }; var items = Enumerable .Range(0, headers.Count) .SelectMany(i => headers.GetValues(i) .Select(v => Tuple.Create(headers.GetKey(i), v))) .Where (x => !heads .Select(y => y.ToString()) .Contains(x.Item1) ) .ToList(); foreach (var item in items) { Request.Headers.Add(item.Item1, item.Item2); } var response = (HttpWebResponse)Request.GetResponse(); return(new StreamReader(response.GetResponseStream()).ReadToEnd()); }
/// <summary> /// /// </summary> /// <param name="header"></param> /// <returns></returns> private static string CanonicalizedUCloudHeaders(WebHeaderCollection header) { string canoncializedUCloudHeaders = string.Empty; SortedDictionary <string, string> headerMap = new SortedDictionary <string, string>(); for (int i = 0; i < header.Count; ++i) { string headerKey = header.GetKey(i); if (headerKey.ToLower().StartsWith("x-ucloud-")) { // ReSharper disable once PossibleNullReferenceException foreach (string value in header.GetValues(i)) { if (headerMap.ContainsKey(headerKey)) { headerMap[headerKey] += value; headerMap[headerKey] += @","; } else { headerMap.Add(headerKey, value); } } } } foreach (KeyValuePair <string, string> item in headerMap) { canoncializedUCloudHeaders += (item.Key + @":" + item.Value + @"\n"); } return(canoncializedUCloudHeaders); }
private string ExtractTicketFromResponse(string contentResponse, WebHeaderCollection headers) { if (!String.IsNullOrEmpty(contentResponse)) { dynamic responseObject = JsonConvert.DeserializeObject <dynamic>(contentResponse.Trim()); if (responseObject["errors"] != null) { foreach (dynamic error in responseObject["errors"]) { if (error.Value.Contains("Your username or password is incorrect")) { throw new InvalidCredentialsException(error.Value); } else if (error.Value.Contains("As a security measure, your account has been disabled")) { throw new InvalidCredentialsException(error.Value); } else if (error.Value.Contains("Username is a required field")) { throw new InvalidCredentialsException(error.Value); } else if (error.Value.Contains("Password is a required field")) { throw new InvalidCredentialsException(error.Value); } else if (error.Value.Contains("Account is not yet active")) { throw new AccountNotVerifiedException(); } } } } Uri location = null; for (int i = 0; i < headers.Count; ++i) { string header = headers.GetKey(i); if (header == "Location") { location = new Uri(headers.GetValues(i)[0]); } } if (location == null) { throw new LoginFailedException(); } var ticketId = HttpUtility.ParseQueryString(location.Query)["ticket"]; if (ticketId == null) { throw new PtcOfflineException(); } return(ticketId); }
void ButtongetitOnClick(object obj, EventArgs ea) { headers.Items.Clear(); cookies.Items.Clear(); response.Items.Clear(); HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(uribox.Text); hwr.CookieContainer = new CookieContainer(); HttpWebResponse hwrsp = (HttpWebResponse)hwr.GetResponse(); WebHeaderCollection whc = hwrsp.Headers; for (int i = 0; i < whc.Count; i++) { headers.Items.Add(whc.GetKey(i) + " = " + whc.Get(i)); } hwrsp.Cookies = hwr.CookieContainer.GetCookies(hwr.RequestUri); foreach (Cookie cky in hwrsp.Cookies) { cookies.Items.Add(cky.Name + " = " + cky.Value); } Stream strm = hwrsp.GetResponseStream(); StreamReader sr = new StreamReader(strm); while (sr.Peek() > -1) { response.Items.Add(sr.ReadLine()); } sr.Close(); strm.Close(); }
public void Request(Uri Url, WebHeaderCollection cHeaders, byte[] baPostdata, string sMPBound, int iPostType, string sFilename, bool bReturnStr) { sResponseCode = ""; msResponse = new MemoryStream(); URI = Url; Filename = sFilename; ReturnStr = bReturnStr; isReady = false; State = ReqState.Connecting; Headers = new WebHeaderCollection(); outHeaders.Add("Host: " + URI.Host); outHeaders.Add("Connection: " + "Close"); outHeaders.Add("User-Agent: pImgDB/" + cb.sAppVer + " (Windows NT 5.1; U; en)"); for (int a = 0; a < cHeaders.Count; a++) { outHeaders.Add(cHeaders.GetKey(a) + ": " + cHeaders.Get(a)); } ConMode = iPostType; if (ConMode != 1) { ConQHdr = "POST"; Postdata = baPostdata; outHeaders.Add("Content-Length: " + Postdata.Length); if (ConMode == 3) { MPBound = sMPBound; ConPHdr = "multipart/form-data; boundary=" + MPBound; } outHeaders.Add("Content-Type: " + ConPHdr); } BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += new DoWorkEventHandler(bw_DoWork); bw.RunWorkerAsync(); }
private HttpResponseMsg CreateResponseMessage(HttpWebResponse webResponse, HttpRequestMessage request) { var httpResponseMessage = new HttpResponseMsg(webResponse.StatusCode) { ReasonPhrase = webResponse.StatusDescription, Version = webResponse.ProtocolVersion, RequestMessage = request }; httpResponseMessage.Content = new ResponseContent(new ResponseStreamWrapper(webResponse)); request.RequestUri = webResponse.ResponseUri; WebHeaderCollection headers = webResponse.Headers; HttpContentHeaders headers2 = httpResponseMessage.Content.Headers; HttpResponseHeaders headers3 = httpResponseMessage.Headers; if (webResponse.ContentLength >= 0L) { headers2.ContentLength = new long?(webResponse.ContentLength); } for (int i = 0; i < headers.Count; i++) { string key = headers.GetKey(i); if (string.Compare(key, "Content-Length", StringComparison.OrdinalIgnoreCase) != 0) { string[] values = headers.GetValues(i); if (!headers3.TryAddWithoutValidation(key, values)) { bool flag = headers2.TryAddWithoutValidation(key, values); } } } return(httpResponseMessage); }
public void HttpRequestHeader_GetKey_Success() { WebHeaderCollection w = new WebHeaderCollection(); w.Add("header1", "value1"); w.Add("header1", "value2"); Assert.NotEmpty(w.GetKey(0)); }
static void Show_HttpHeader(WebHeaderCollection http_header) { MainForm.WriteStatus("+++ リクエストヘッダ出力\r\n"); for (int i = 0; i < http_header.Count; i++) { MainForm.WriteStatus($"{http_header.GetKey(i)} = {http_header.Get(i)}\r\n"); } }
static int Main(string[] args) { if (args.Length <= 0) { DisplayHelp(); } else { try { string suri = args[0].ToString(); Uri uri = new Uri(args[0].ToString()); WebClient myWebClient = new WebClient(); myWebClient.OpenRead(suri); WebHeaderCollection myWebHeaderCollection = myWebClient.ResponseHeaders; Console.WriteLine("\nDisplaying the Server Header\n"); for (int i = 0; i < myWebHeaderCollection.Count; i++) { Console.WriteLine("\t" + myWebHeaderCollection.GetKey(i) + " = " + myWebHeaderCollection.Get(i)); } Console.WriteLine("\nDisplaying the Server OPTIONS Fingerprint\n"); byte[] byteArray = Encoding.ASCII.GetBytes("Hello"); byte[] responseArray = myWebClient.UploadData(suri, "OPTIONS", byteArray); myWebHeaderCollection = myWebClient.ResponseHeaders; for (int i = 0; i < myWebHeaderCollection.Count; i++) { Console.WriteLine("\t" + myWebHeaderCollection.GetKey(i) + " = " + myWebHeaderCollection.Get(i)); } return(0); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } return(1); }
/// <summary> /// headle response headers /// </summary> /// <param name="response"></param> /// <param name="httpWebResponse"></param> private static void HandleHttpWebResponseHeaders(Response response, HttpWebResponse httpWebResponse) { response.Code = (int)httpWebResponse.StatusCode; response.Message = httpWebResponse.StatusDescription; WebHeaderCollection headers = httpWebResponse.Headers; // Transfer-Encoding: chunked bool isChunked = false; if (headers != null) { Dictionary <string, List <string> > result = new Dictionary <string, List <string> >(headers.Count); for (int i = 0; i < headers.Count; i++) { List <string> values = null; string key = headers.GetKey(i); if (headers.GetValues(i) != null) { values = new List <string>(); foreach (string value in headers.GetValues(i)) { values.Add(value); } } result.Add(key, values); if ("Transfer-Encoding".EndsWith(key, StringComparison.OrdinalIgnoreCase) && values.Contains("chunked")) { isChunked = true; } } response.Headers = result; } if (!isChunked) { response.ContentLength = httpWebResponse.ContentLength; } response.ContentType = httpWebResponse.ContentType; if (response.Body != null) { if (!isChunked) { response.Body.ContentLength = httpWebResponse.ContentLength; } response.Body.ContentType = httpWebResponse.ContentType; } //handle header response.HandleResponseHeader(); }
protected string GetHeaderString() { StringBuilder headerBuilder = new StringBuilder(); for (int i = 0; i < headers.Count; i++) { headerBuilder.AppendFormat("header: {0}={1}", headers.GetKey(i), headers.Get(i)).AppendLine(); } return(headerBuilder.ToString()); }
public static Dictionary <string, string> ConvertHeaders(WebHeaderCollection headers) { var result = new Dictionary <string, string>(); for (int i = 0; i < headers.Count; i++) { result.Add(TeaConverter.StrToLower(headers.GetKey(i)), headers.Get(i)); } return(result); }
public void GetKey_Fail() { WebHeaderCollection w = new WebHeaderCollection(); w.Add("Accept", "text/plain"); Assert.Throws<ArgumentOutOfRangeException>(() => w.GetKey(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => w.GetKey(42)); }
public void GetKey_Success() { const string key = "Accept"; const string key2 = "Content-Length"; WebHeaderCollection w = new WebHeaderCollection(); w.Add(key, "text/plain"); w.Add(key2, "123"); Assert.Equal(key, w.GetKey(0)); Assert.Equal(key2, w.GetKey(1)); }
public Hashtable ExecRequest( string Cmd, string ContentType, string Content, WebHeaderCollection hds, bool GetResponse ) { byte [] buf; string line; string req = String.Format( "{0} {1} RTSP/1.0\r\n" + "CSeq: {2}\r\n", Cmd, url, ++cseq ); if( session != null ) req += String.Format( "Session: {0}\r\n", session ); if( hds != null ) { for( int i = 0; i < hds.Count; i++ ) { req += String.Format( "{0}: {1}\r\n", hds.GetKey( i ), hds.Get( i ) ); } } if( ContentType != null && Content != null ) { req += String.Format( "Content-Type: {0}\r\n" + "Content-Length: {1}\r\n", ContentType, Content.Length ); } req += String.Format( "User-Agent: {0}\r\n", useragent ); for( int i = 0; i < addheaders.Count; i++ ) { req += String.Format( "{0}: {1}\r\n", addheaders.GetKey( i ), addheaders.Get( i ) ); } req += "\r\n"; if( ContentType != null && Content != null ) req += Content; buf = Encoding.ASCII.GetBytes( req ); nsctrl.Write( buf, 0, buf.Length ); if( !GetResponse ) return null; line = srctrl.ReadLine(); if( line == null || line == "" ) throw new Exception( "Request failed, read error" ); string [] tokens = line.Split( new char[] { ' ' } ); if( tokens.Length != 3 || tokens[ 1 ] != "200" ) throw new Exception( "Request failed, error " + tokens[ 1 ] ); string name = null; Hashtable ht = new Hashtable(); while( ( line = srctrl.ReadLine() ) != null && line != "" ) { if( name != null && Char.IsWhiteSpace( line[ 0 ] ) ) { ht[ name ] += line; continue; } int i = line.IndexOf( ":" ); if( i == -1 ) throw new Exception( "Request failed, bad header" ); name = line.Substring( 0, i ); ht[ name ] = line.Substring( i + 1 ).Trim(); } return ht; }