Изпратете POST заявка с бисквитка и получете съдържание

Създавам тестове за моето Web API MVC приложение и се опитвам да изпратя POST заявка. Трябва да изпратя бисквитка и след това да прочета съдържанието, което получавам от отговора.

Опитах се да използвам HttpWebRequest и той работи чудесно с бисквитката (получавам StatusCode OK), но не мога да прочета съдържанието от отговора:

public static HttpWebResponse WebRequest(string methodURL, string method, string json, HttpCookie cookie)
        {
            string URL = baseURL + methodURL;
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.CreateHttp(URL);
            httpWebRequest.ContentType = "text/json";
            httpWebRequest.Method = method;
            httpWebRequest.Headers.Add("Cookie", cookie.Name+"="+cookie.Value);
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write(json);
                streamWriter.Close();
            }
            try
            {
                return (HttpWebResponse)httpWebRequest.GetResponse();
            }
            catch (System.Net.WebException ex)
            {
                using (WebResponse response = ex.Response)
                {
                    return (HttpWebResponse)response;
                }
            }
        }

След това се опитах да използвам HttpResponseMessage, за да върна съдържанието, но не можах да изпратя бисквитката правилно - получавам StatusCode „Unauthorized“.

 public static HttpResponseMessage WebRequest(string methodURL, string method, string json, HttpCookie cookie)
        {
            string URL = baseURL + methodURL;

            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(URL);
            client.DefaultRequestHeaders
                  .Accept
                  .Add(new MediaTypeWithQualityHeaderValue("text/json"));
            client.DefaultRequestHeaders.Add("Cookie", cookie.Name + "=" + cookie.Value);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, URL);
            request.Content = new StringContent(json, Encoding.UTF8, "text/json");
            request.Headers.Add("Cookie", cookie.Name + "=" + cookie.Value);
            request.Properties.Add("Cookie", cookie.Name + "=" + cookie.Value);
            Task<HttpResponseMessage> r  = client.SendAsync(request)
              .ContinueWith(responseTask =>
              {
                  HttpResponseMessage message = responseTask.Result;
                  message.Headers.Add("Cookie", cookie.Name + "=" + cookie.Value);
                  return message;

              });
            return r.Result;
        }

Някакви идеи?


person TamarG    schedule 15.08.2015    source източник


Отговори (1)


За първия начин трябва да използвате cookieContainer

httpWebRequest.CookieContainer = new CookieContainer();
httpWebRequest.CookieContainer.Add(cookie);

за да прочетете отговора, можете да използвате нещо подобно,

var responseStr = new StringBuilder();
try
{
    var response = (HttpWebResponse) httpWebRequest.GetResponse();
    var responseCode = response.StatusCode;

    var receiveStream = response.GetResponseStream();
    if (receiveStream != null)
    {
        var instr = new StreamReader(receiveStream, Encoding.UTF8);
        String inputLine;
        while ((inputLine = instr.ReadLine()) != null)
        {
            responseStr.Append(inputLine);
        }
        instr.Close();
    }
} catch (Exception e)
{
}
person davcs86    schedule 15.08.2015
comment
Нямам клиент.CookieContaine - person TamarG; 16.08.2015
comment
Във вашия случай ще бъде httpWebRequest.CookieContainer - person davcs86; 16.08.2015