public static string HttpGet(string Url, string cookie) { try { HttpClientHandler handler = new HttpClientHandler() { UseCookies = true }; using (HttpClient client = new HttpClient(handler)) { client.DefaultRequestHeaders.Connection.Add("keep-alive"); client.DefaultRequestHeaders.Add("Cookie", cookie); HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Get, Url); HttpResponseMessage response = client.SendAsync(message).Result; System.Net.Http.Headers.HttpResponseHeaders heads = response.Headers; string cookie1 = response.RequestMessage.Headers.ToString();//从这个里边把sessionid的cookie拿到 byte[] resultBytes = response.Content.ReadAsByteArrayAsync().Result; return(Encoding.GetEncoding("GB2312").GetString(resultBytes)); } } catch (Exception) { return(null); } }
public WebApiRequestException(string message, System.Net.HttpStatusCode statusCode, string response, System.Net.Http.Headers.HttpResponseHeaders headers, System.Net.Http.Headers.MediaTypeHeaderValue contentType) : base(message) { StatusCode = statusCode; Response = response; Headers = headers; ContentType = contentType; }
public void reply(HttpListenerContext context, System.Net.Http.Headers.HttpResponseHeaders headers, String responsePayload) { try { Log.InfoFormat("Sending reply:\nHeaders:\n{0}\nPayload:\n{1}", toS(HeadersToString(headers)), toS(responsePayload)); // Obtain a response object. HttpListenerResponse response = context.Response; // Construct a response. byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responsePayload); // Get a response stream and write the response to it. response.ContentLength64 = buffer.Length; response.ContentType = context.Request.ContentType; response.ContentEncoding = context.Request.ContentEncoding; System.IO.Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); output.Close(); context.Response.Close(); } catch (Exception e) { Log.Error("Failed to return the reply", e); throw e; } }
/// <summary> /// Creates a new service exception. /// </summary> /// <param name="error">The error that triggered the exception.</param> /// <param name="innerException">The possible innerException.</param> /// <param name="responseHeaders">The HTTP response headers from the response.</param> /// <param name="statusCode">The HTTP status code from the response.</param> public ServiceException(Error error, System.Net.Http.Headers.HttpResponseHeaders responseHeaders, System.Net.HttpStatusCode statusCode, Exception innerException = null) : base(error?.ToString(), innerException) { this.Error = error; this.ResponseHeaders = responseHeaders; this.StatusCode = statusCode; }
public void PostFileStatusTest() { HttpResponseMessage response = new HttpResponseMessage(); HttpContent content = null; content.Headers.Add("string1", "string1"); System.Net.Http.Headers.HttpResponseHeaders header = null; header.Add("string1", "string1"); response.Content = content; response.Headers.Add("string1", "string1"); response.IsSuccessStatusCode.Equals(true); response.ReasonPhrase.Equals("string1"); response.RequestMessage.Content.Headers.Add("string1", "string1"); response.StatusCode.Equals("Success"); response.Version.Major.Equals(1); UploadManagerController target = new UploadManagerController(); // TODO: Initialize to an appropriate value HttpResponseMessage expected = null; // TODO: Initialize to an appropriate value HttpResponseMessage actual; actual = target.PostFileStatus(); Assert.AreEqual(expected, actual); //Assert.Inconclusive("Verify the correctness of this test method."); }
public static string HttpPost(string Url, string cookie, IEnumerable <KeyValuePair <string, string> > postDataStr) { try { using (HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false, AllowAutoRedirect = false })) { client.DefaultRequestHeaders.Connection.Add("keep-alive"); client.DefaultRequestHeaders.Add("Cookie", cookie); HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, Url) { Content = new FormUrlEncodedContent(postDataStr) }; HttpResponseMessage response = client.SendAsync(message).Result; System.Net.Http.Headers.HttpResponseHeaders heads = response.Headers; string cookie1 = response.RequestMessage.Headers.ToString(); byte[] resultBytes = response.Content.ReadAsByteArrayAsync().Result; return(Encoding.GetEncoding("GB2312").GetString(resultBytes)); } } catch (Exception) { return(null); } }
public void GetTest() { HttpResponseMessage response = new HttpResponseMessage(); //var formVars = new Dictionary<string,string>(); //formVars.Add("message", "Some Value"); //var content = new FormUrlEncodedContent(formVars); HttpContent content = null; content.Headers.Add("string1", "string1"); System.Net.Http.Headers.HttpResponseHeaders header = null; header.Add("string1", "string1"); response.Content = content; response.Headers.Add("string1", "string1"); response.IsSuccessStatusCode.Equals(true); response.ReasonPhrase.Equals("string1"); response.RequestMessage.Content.Headers.Add("string1", "string1"); response.StatusCode.Equals(null); response.Version.Major.Equals(1); SharedAccessSignatureController target = new SharedAccessSignatureController(); // TODO: Initialize to an appropriate value HttpResponseMessage expected = response; // TODO: Initialize to an appropriate value HttpResponseMessage actual; actual = target.Get(); Assert.AreEqual(expected, actual); // Assert.Inconclusive("Verify the correctness of this test method."); }
public HttpResponseHeaders(System.Net.Http.Headers.HttpResponseHeaders containedObject) { if ((containedObject == null)) { throw new System.ArgumentNullException("containedObject"); } this.containedObject = containedObject; }
public ApiResponse(System.Net.Http.HttpResponseMessage response, string rawContent) { StatusCode = response.StatusCode; Headers = response.Headers; IsSuccessStatusCode = response.IsSuccessStatusCode; ReasonPhrase = response.ReasonPhrase; RawContent = rawContent; }
/// <summary> /// Creates a new service exception. /// </summary> /// <param name="error">The error that triggered the exception.</param> /// <param name="innerException">The possible innerException.</param> /// <param name="responseHeaders">The HTTP response headers from the response.</param> /// <param name="statusCode">The HTTP status code from the response.</param> /// <param name="rawResponseBody">The raw JSON response body.</param> public ServiceException(Error error, System.Net.Http.Headers.HttpResponseHeaders responseHeaders, System.Net.HttpStatusCode statusCode, string rawResponseBody, Exception innerException = null) : this(error, responseHeaders, statusCode, innerException) { this.RawResponseBody = rawResponseBody; }
public void get(String url) { HttpClientHandler handler = new HttpClientHandler(); handler.CookieContainer.Add(new Cookie("name", "leegean", "/", "baidu.com")); HttpClient httpClient = new HttpClient(handler); System.Net.Http.Headers.HttpRequestHeaders reqHeader = httpClient.DefaultRequestHeaders; reqHeader.Host = "baidu.com"; // 创建一个异步GET请求,当请求返回时继续处理 httpClient.GetAsync(url).ContinueWith( (requestTask) => { if (requestTask.IsFaulted) { Console.WriteLine(requestTask.Exception); } else { HttpResponseMessage response = requestTask.Result; headers = response.Headers; enumerator = headers.GetEnumerator(); while (enumerator.MoveNext()) { KeyValuePair <String, IEnumerable <String> > pair = enumerator.Current; Console.WriteLine(pair.Key + " " + pair.Value); } CookieCollection cookies = handler.CookieContainer.GetCookies(new Uri(url)); foreach (Cookie cookie in cookies) { Console.WriteLine(cookie.Name + " " + cookie.Value); } // 确认响应成功,否则抛出异常 if (response.IsSuccessStatusCode) { response.Content.ReadAsStringAsync().ContinueWith( (readTask) => Console.WriteLine(readTask.Result.Substring(0, 100))); } else if (response.StatusCode != HttpStatusCode.OK) { Console.WriteLine(response.StatusCode + " " + response.ReasonPhrase); } } }); Console.WriteLine("Hit enter to exit..."); //Console.ReadLine(); }
public static PagingInfo FindAndParsePagingInfo(System.Net.Http.Headers.HttpResponseHeaders responseHeaders) { IEnumerable <string> paginationHeaderValues; responseHeaders.TryGetValues("X-Pagination", out paginationHeaderValues); if (paginationHeaderValues.Any()) { return(JsonConvert.DeserializeObject <PagingInfo>(paginationHeaderValues.FirstOrDefault())); } else { return(null); } }
public static string GetNextURL(this System.Net.Http.Headers.HttpResponseHeaders headers) { Regex reg = new Regex(@"<(\S*)>"); IEnumerable <string> links; headers.TryGetValues("Link", out links); string Url = links.First().Split(',').FirstOrDefault(s => s.Contains("rel=\"next\"")); if (Url != null) { return(Url = reg.Match(Url).Groups[1].Value); } else { return(null); } }
/// <summary> /// Copies headers from one <see cref="System.Net.Http.HttpResponseMessage"/> instance to another. /// </summary> /// <param name="source">The source <see cref="System.Net.Http.HttpResponseMessage"/> to copy from.</param> /// <param name="destination">The destination <see cref="System.Net.Http.HttpResponseMessage"/> to copy to.</param> public static void CopyHeadersTo(this System.Net.Http.Headers.HttpResponseHeaders source, System.Net.Http.Headers.HttpResponseHeaders destination) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (destination == null) { throw new ArgumentNullException(nameof(destination)); } foreach (var header in source) { if (destination.Contains(header.Key)) { destination.Remove(header.Key); } destination.Add(header.Key, header.Value); } }
public static void AddCookies(this System.Net.Http.Headers.HttpResponseHeaders headers, System.Collections.Generic.IEnumerable <System.Net.Http.Headers.CookieHeaderValue> cookies) { }
public static void CopyHeadersTo(this System.Net.Http.Headers.HttpResponseHeaders source, System.Net.Http.Headers.HttpResponseHeaders destination) { Helper.Throw(); }
public String HeadersToString(System.Net.Http.Headers.HttpResponseHeaders headers) { return(String.Join("\n", headers.Select(x => String.Format("\t{0}={1}", x.Key, String.Join(",", x.Value))) )); }
public async Task <ActionResult> Login(LoginM data) { if (!ModelState.IsValid) { return(View()); } model = data; client.BaseAddress = CommonData.ApiUrl; var jsonString = JsonConvert.SerializeObject(model); var content = new StringContent(jsonString, Encoding.UTF8, "application/json"); IEnumerable <string> found; try { HttpResponseMessage responseFromRequest = await client.PostAsync("api/ExternalLogin", content); if (responseFromRequest != null) { System.Net.Http.Headers.HttpResponseHeaders headers = responseFromRequest.Headers; if (headers.Contains("Found")) { if (headers.TryGetValues("Found", out found) && found.ToArray()[0] == "true") { if (headers.Contains("EmployeeID")) { EmployeeID = headers.GetValues("EmployeeID").ToString(); Session["UserName"] = model.UserName; Session["SafetyLogged"] = true; return(RedirectToAction("", "")); } else if (headers.Contains("WrongPassword")) { ViewBag.Error = "Password doesn't match."; return(RedirectToAction("Login", "Login")); } } else if (headers.TryGetValues("Found", out found) && found.ToArray()[0] == "false") { if (headers.Contains("UserNotFound")) { ViewBag.Error = "Username not found"; return(RedirectToAction("", "")); } else if (headers.Contains("WrongPassword")) { ViewBag.Error = "Password incorrect"; return(RedirectToAction("", "")); } } } } ViewBag.Error = "Internal issue, please try again later."; return(RedirectToAction("", "")); } catch (Exception exc) { ViewBag.Message = "Internar server error, but you'll be redirected anyway." + exc.Message; return(RedirectToAction("Index", "Home")); } //return View(); }
private async Task <bool> ValidateLogin() { client.BaseAddress = CommonData.ApiUrl; var jsonString = JsonConvert.SerializeObject(model); var content = new StringContent(jsonString, Encoding.UTF8, "application/json"); IEnumerable <string> found; try { HttpResponseMessage responseFromRequest = await client.PostAsync("api/ExternalLogin", content); if (responseFromRequest != null) { System.Net.Http.Headers.HttpResponseHeaders headers = responseFromRequest.Headers; if (headers.Contains("Found")) { if (headers.TryGetValues("Found", out found) && found.ToArray()[0] == "true") { if (headers.Contains("EmployeeID")) { EmployeeID = headers.GetValues("EmployeeID").ToString(); Session["UserName"] = model.UserName; Session["SafetyLogged"] = true; return(true); } else if (headers.Contains("WrongPassword")) { ViewBag.Error = "Password doesn't match."; return(false); } } else if (headers.TryGetValues("Found", out found) && found.ToArray()[0] == "false") { if (headers.Contains("UserNotFound")) { ViewBag.Error = "Username not found"; return(false); } else if (headers.Contains("WrongPassword")) { ViewBag.Error = "Password incorrect"; return(false); } } } } ViewBag.Error = "Internal issue, please try again later."; return(false); } catch (Exception exc) { Response.Write("<script>alert('" + Server.HtmlEncode(exc.Message) + "')</>"); return(false); } #region validationUsingEntFramework //parkingEntities entity = new parkingEntities(); ////using linq to find user //var result = entity.SystemUsers.FirstOrDefault(m => m.LoginUserName == loginData.UserName); //if (result != null) //{ // var userAndPass = entity.SystemUsers.FirstOrDefault(m => m.LoginUserName == loginData.UserName && m.LoginPassword == loginData.Password); // if(userAndPass != null) // { // Session["UserName"] = result.LoginUserName; // Session["SafetyLogged"] = true; // return RedirectToAction("Index", "Home"); // } // else // { // ViewBag.WrongData = "Wrong password."; // return View("Login"); // } //} //else //{ // ViewBag.LoginError = "User ot found."; // return View("Login"); //} #endregion }