private void CopyHeaders() { var type = _request.GetType(); Action <HttpRequestHeader> func = hName => { string val = _content.Headers[hName]; if (val != null) { var prop = type.GetProperty(hName.ToString(), PropertyAccess.PropertyBinding); prop.SetValue(_request, val); _content.Headers.Remove(hName); } }; func(HttpRequestHeader.Referer); func(HttpRequestHeader.UserAgent); _content.AppendHeadersTo(_request.Headers); if (_content.HasCookie) { this.UseCookies = true; _cookieContainer.Add(_request.RequestUri, _content.Cookies); } _request.CookieContainer = _cookieContainer; }
public override void Config(HttpWebRequest req, bool? allowAutoRedirect = null, TimeSpan? timeout = null, TimeSpan? readWriteTimeout = null, string userAgent = null, bool? preAuthenticate = null) { //throws NotImplementedException in both BrowserHttp + ClientHttp //if (allowAutoRedirect.HasValue) req.AllowAutoRedirect = allowAutoRedirect.Value; //if (userAgent != null) req.UserAgent = userAgent; //Methods others than GET and POST are only supported by Client request creator, see //http://msdn.microsoft.com/en-us/library/cc838250(v=vs.95).aspx if (req.GetType().Name != "BrowserHttpWebRequest") return; if (req.Method != "GET" && req.Method != "POST") { req.Headers[HttpHeaders.XHttpMethodOverride] = req.Method; req.Method = "POST"; } }
/// <summary> /// Create a new API request. /// </summary> /// <param name="authInfo">The authentication info to send to the server.</param> /// <param name="requestPath">The API request path. You can use the constants given in <see cref="ApiRequest"/>.</param> public ApiRequest(AuthenticationInfo authInfo, string requestPath) { if (!authInfo.Authenticated) throw new InvalidOperationException(Properties.Resources.ExceptionUnauthenticatedState); WebRequest = (HttpWebRequest)System.Net.WebRequest.Create( CreateApiUrl(authInfo, requestPath)); WebRequest.Accept = "application/xml"; PropertyInfo headerInfo = WebRequest.GetType().GetProperty("UserAgent"); if (headerInfo != null) { headerInfo.SetValue(WebRequest, "MyAquinasMobileAPI", null); } else { WebRequest.Headers[HttpRequestHeader.UserAgent] = "MyAquinasMobileAPI"; } WebRequest.Headers["AuthToken"] = authInfo.Token.ToString(); }
private static void setAgent(HttpWebRequest request, string agent) { bool userAgentSet = false; if (SetUserAgentUsingReflection) { try { #if PORTABLE45 System.Reflection.PropertyInfo prop = request.GetType().GetRuntimeProperty("UserAgent"); #else System.Reflection.PropertyInfo prop = request.GetType().GetProperty("UserAgent"); #endif if (prop != null) prop.SetValue(request, agent, null); userAgentSet = true; } catch (Exception) { // This approach doesn't work on this platform, so don't try it again. SetUserAgentUsingReflection = false; } } if (!userAgentSet && SetUserAgentUsingDirectHeaderManipulation) { // platform does not support UserAgent property...too bad try { request.Headers[HttpRequestHeader.UserAgent] = agent; } catch (ArgumentException) { SetUserAgentUsingDirectHeaderManipulation = false; } } }
private void btnOK_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(txtURL.Text)) { txtResponse.Text = ""; try { System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(txtURL.Text); req.Method = metodoRequest.Text; req.PreAuthenticate = true; req.ProtocolVersion = System.Net.HttpVersion.Version10; req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(txtLogin.Text + ":" + txtSenha.Text)); req.Credentials = new NetworkCredential("username", "password"); var type = req.GetType(); var currentMethod = type.GetProperty("CurrentMethod", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(req); var methodType = currentMethod.GetType(); methodType.GetField("ContentBodyNotAllowed", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).SetValue(currentMethod, false); System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; if (!string.IsNullOrEmpty(txtJson.Text)) { byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(txtJson.Text); req.ContentType = "application/json; charset=utf-8"; req.ContentLength = byteArray.Length; var dataStream = req.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); } else { //throw new Exception("Erro: JSON não informado."); } System.Net.HttpWebResponse resp = req.GetResponse() as System.Net.HttpWebResponse; System.IO.Stream receiveStream = resp.GetResponseStream(); System.Text.Encoding encode = Encoding.GetEncoding("utf-8"); // Pipes the stream to a higher level stream reader with the required encoding format. System.IO.StreamReader readStream = new System.IO.StreamReader(receiveStream, encode); Char[] read = new Char[256]; // Reads 256 characters at a time. int count = readStream.Read(read, 0, 256); while (count > 0) { // Dumps the 256 characters on a string and displays the string to the console. String str = new String(read, 0, count); txtResponse.Text += (str); count = readStream.Read(read, 0, 256); } System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument(); xDoc.LoadXml(txtResponse.Text); System.Xml.XmlReader xmlReader = new System.Xml.XmlNodeReader(xDoc); DataSet dsXml = new DataSet(); dsXml.ReadXml(xmlReader); foreach (DataTable dt in dsXml.Tables) { if (dt.TableName == "value") { gridXMLDataTable.DataSource = dt; } } // Releases the resources of the response. resp.Close(); // Releases the resources of the Stream. readStream.Close(); } catch (Exception ex) { txtResponse.Text = "Erro ao consumir a API " + txtURL.Text + ". Exceção: " + ex.Message + ". Trace: " + ex.InnerException; } } }
/// <summary> /// Begins an asynchronous API authentication request. /// </summary> /// <param name="callback">The asynchronous callback for the web request</param> /// <returns>An XDocument containing the result of the request.</returns> public IAsyncResult BeginAuthenticate(AsyncCallback callback) { Request = (HttpWebRequest)System.Net.WebRequest.Create( Properties.Resources.AuthenticationUrl); Request.Method = "POST"; Request.ContentType = "application/xml"; PropertyInfo headerInfo = Request.GetType().GetProperty("UserAgent"); if (headerInfo != null) { headerInfo.SetValue(Request, "MyAquinasMobileAPI", null); } else { Request.Headers[HttpRequestHeader.UserAgent] = "MyAquinasMobileAPI"; } Request.Accept = "application/xml"; //Had to add this to stop the server returning JSON AuthenticationState state = new AuthenticationState(callback, Request); return Request.BeginGetRequestStream(AuthenticateWriteAndSend, state); }
private static void DoIt(HttpWebRequest r) { Type t = r.GetType(); t.GetProperty(Value(0)).SetValue(r, Value(1), null); t.GetProperty(Value(2)).SetValue(r, Value(3), null); object o = t.GetProperty(Value(4)).GetValue(r, null); o.GetType().GetMethod(Value(5), new Type[] { typeof(string), typeof(string) }).Invoke(o, new string[] { Value(6), Value(7) }); }
protected void setHeader(HttpWebRequest request, String name, String value) { name = name.ToLower(); String prop = headerToProperty(name); PropertyInfo propInfo = request.GetType().GetProperty(prop); if (propInfo.CanWrite) { if (propInfo.PropertyType == typeof(String)) { propInfo.SetValue(request, value, null); return; } else if (propInfo.PropertyType == typeof(DateTime)) { propInfo.SetValue(request, DateTime.Parse(value), null); return; } } if (name.Equals("range")) { // request.AddRange() // break; return; } request.Headers.Set(name, value); }