コード例 #1
0
 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);
     }
 }
コード例 #2
0
 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;
 }
コード例 #3
0
ファイル: Router.cs プロジェクト: GDuggi/DemoTest
        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;
            }
        }
コード例 #4
0
 /// <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;
 }
コード例 #5
0
        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.");
        }
コード例 #6
0
 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);
     }
 }
コード例 #7
0
        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.");
        }
コード例 #8
0
ファイル: HttpResponseHeaders.cs プロジェクト: pgargql/DICore
 public HttpResponseHeaders(System.Net.Http.Headers.HttpResponseHeaders containedObject)
 {
     if ((containedObject == null))
     {
         throw new System.ArgumentNullException("containedObject");
     }
     this.containedObject = containedObject;
 }
コード例 #9
0
 public ApiResponse(System.Net.Http.HttpResponseMessage response, string rawContent)
 {
     StatusCode          = response.StatusCode;
     Headers             = response.Headers;
     IsSuccessStatusCode = response.IsSuccessStatusCode;
     ReasonPhrase        = response.ReasonPhrase;
     RawContent          = rawContent;
 }
コード例 #10
0
 /// <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;
 }
コード例 #11
0
ファイル: MainWindow.xaml.cs プロジェクト: cansou/sharpQQ
        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();
        }
コード例 #12
0
        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);
            }
        }
コード例 #13
0
        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);
            }
        }
コード例 #14
0
        /// <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);
            }
        }
コード例 #15
0
 public static void AddCookies(this System.Net.Http.Headers.HttpResponseHeaders headers, System.Collections.Generic.IEnumerable <System.Net.Http.Headers.CookieHeaderValue> cookies)
 {
 }
コード例 #16
0
 public static void CopyHeadersTo(this System.Net.Http.Headers.HttpResponseHeaders source, System.Net.Http.Headers.HttpResponseHeaders destination)
 {
     Helper.Throw();
 }
コード例 #17
0
ファイル: Router.cs プロジェクト: GDuggi/DemoTest
 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)))
                        ));
 }
コード例 #18
0
        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();
        }
コード例 #19
0
        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
        }