我正在为我的Web API MVC应用程序构建测试,而我正在尝试发送POST请求。我需要发送一个cookie,然后阅读我从回复中得到的内容。
我尝试使用HttpWebRequest
并且它与Cookie一起工作得很好(我得到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
来获取内容,但我无法正确发送cookie - 我将StatusCode“未经授权”。
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;
}
有什么想法吗?
答案 0 :(得分:0)
首先,您必须使用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)
{
}