I want to make a Json Post Request with my Windows Universal App.
I have it working in my Android and IOS.
public String DoServiceCall()
{
var request = (HttpWebRequest)WebRequest.Create(string.Format("{2}/{0}/{0}ServiceJson.svc/{1}", "Authentication", "Authenticate", "https://....."));
using (MemoryStream ms = new MemoryStream())
{
// create the request object
string requestString = JSONRequest;
byte[] requestData = Encoding.UTF8.GetBytes(requestString);
request.Method = "POST";
request.ContentType = "application/json; charset=UTF-8";
request.ContentLength = requestData.Length;
request.AllowAutoRedirect = false;
// add known cookies to request (needed for authentication)
CookieContainer requestCookies = new CookieContainer();
foreach (Cookie knownCookie in this._cookieCollection)
{
requestCookies.Add( knownCookie);
}
request.CookieContainer = requestCookies;
//For getting rid of the https Problem
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
using (Stream stream = request.GetRequestStream())
{
stream.Write(requestData, 0, requestData.Length);
}
// get response data
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
return (responseString);
}
}
The Problem is that Windows Universal does not support.
request.ContentLength = requestData.Length;
request.AllowAutoRedirect = false;
requestCookies.Add( knownCookie); //with only one Argument
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
Neither does it support.
request.GetRequestStream())
(HttpWebResponse) request.GetResponse();
But that i could fix with async
await request.GetRequestStreamAsync())
(HttpWebResponse)await request.GetResponseAsync();
But without that 4 Lines i couldn´t get it working on Windows.
I just doesn´t get any Response.
Is there an Option to get it working on Windows 10 or is there an Working alternative.
So i finally found a solution.
Based on the Comment i tried the HttpClient.
But the Stanard Httpclient in the system namespace doesn`t support filter, which i need to get pass the SSL certificat problem.
Luckly in the Windows.Web.Http namespace, there is another HttpClient, which suppports filters.
The answer is the fully functional HttpClient Post Call.
public async void testcallwind()
{
List<HttpCookie> cookieCollection = new List<HttpCookie>();
HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
HttpClient httpClient;
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);//Allow untrusted CA's
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired);
// add known cookies to request (needed for authentication)
foreach (HttpCookie knownCookie in cookieCollection)
{
filter.CookieManager.SetCookie(knownCookie);
}
httpClient = new HttpClient(filter);
string resourceAddress = string.Format("https://...");
string requestString = "{\"request\":{\"CallerState\":null,...."}}";
byte[] requestData = Encoding.UTF8.GetBytes(requestString);
UnicodeEncoding en = new UnicodeEncoding();
IHttpContent content = new HttpStringContent(requestString, 0, "application/json");
Uri postBody = new Uri(resourceAddress);
var response = await httpClient.PostAsync(postBody, content);
httpClient.Dispose();
var test = response.Content;
}
Related
I have a web app hosted in azure. When I use postman to make the request I get a
json result, which is the correcet response. When I try to make the same request via C# using the same token I receive a errpr - The remote server returned an error: (401) Unauthorized.
here is the code I use to make the request.
public string RequestData(string queryString, string token)
{
var request = (HttpWebRequest)WebRequest.Create(queryString);
request.Proxy = GetProxy();
request.Credentials = CredentialCache.DefaultCredentials;
request.PreAuthenticate = true;
request.UseDefaultCredentials = true;
request.Method = "GET";
request.ContentType = "application/json";
request.ContentLength = 0;
request.CookieContainer = new CookieContainer();
request.Headers.Add("authorization", "Bearer " + token);
using (var webresponse = request.GetResponse())
{
if (webresponse.GetResponseStream() == Stream.Null)
{
throw new Exception("Response stream is empty");
}
var response = (HttpWebResponse)webresponse;
if (response.StatusCode != HttpStatusCode.OK)
{
return response.StatusCode.ToString();
}
else
{
return response.StatusCode.ToString();
}
}
}
I have double checked the token to ensure it is correct and it is.
Another point I wanted to mention is that it did not work initially in
Postman without enabling Interceptor. This goes for Advanced Rest Client.
The request did not work until I enabled "XHR" and installed ARC cookie exchange.
I have checked the request headers in Fiddler and noticed there are no additional headers except for the authorization one (which I add as well).
UPDATE:
I got a successfull response in Postman (https://www.getpostman.com/)
and ran the code it generated for c# using RestSharp. In the response
the error thrown was
"You do not have permission to view this directory or page."
Which points to the token not being correct. Which is confusing since it works
in Postman and Advanced Rest Client. Also I must mention I retrieve the token
on each call using the clientid and secret using the following code:
public async static Task<AzureAccessToken> CreateOAuthAuthorizationToken(string clientId, string clientSecret, string resourceId, string tenantId)
{
AzureAccessToken token = null;
var oauthUrl=string.Format("https://login.microsoftonline.com/{0}/oauth2/token", tenantId);
var reqBody = String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}",clientId, clientSecret);
var client = new HttpClient();
HttpContent content = new StringContent(reqBody);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
using (HttpResponseMessage response = await client.PostAsync(oauthUrl, content))
{
if (response.IsSuccessStatusCode)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AzureAccessToken));
Stream json = await response.Content.ReadAsStreamAsync();
token = (AzureAccessToken)serializer.ReadObject(json);
return token;
}
return null;
}
}
after checking the log in azure, I saw the following error message:
JWT validation failed: IDX10214: Audience validation failed. Audiences: '00000002-0000-0000-c000-000000000000'. Did not match: validationParameters.ValidAudience: 'f50a9d02-b8f4-408f-aaf8-0046e6cbf7a6' or validationParameters.ValidAudiences: 'null'.
I resolved the issue by adding '00000002-0000-0000-c000-000000000000' to the "Allowed Token Audiences" under Azure Active Directory Settings.
I have called third party API. When I use postman to make the request I get a json result, which is the correct response. When I try to make the same request via C# using the same token I receive a error - The remote server returned an error: (401) Unauthorized. Finally I got the solution.
When I make the login request some cookies will send by the server and that cookie will store in postman. If you see code snippet you will see information about request that is raised by postman.
When I call the Login method I stored the cookies like below:
public ResponseData OnGetResponseFromAPI(string URL, string Method, string PostData = null, Dictionary<string, string> Headers = null, string body = null, string ContentType = "application/json")
{
ResponseData response = new ResponseData();
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
var webRequest = (HttpWebRequest)WebRequest.Create(URL);
CookieContainer cookieJar = new CookieContainer();
webRequest.CookieContainer = cookieJar;
webRequest.Method = Method;
webRequest.ContentType = ContentType;
if (Method == "GET")
{
var type = webRequest.GetType();
var currentMethod = type.GetProperty("CurrentMethod", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(webRequest);
var methodType = currentMethod.GetType();
methodType.GetField("ContentBodyNotAllowed", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(currentMethod, false);
}
if (Headers == null)
Headers = new Dictionary<string, string>();
foreach (KeyValuePair<string, string> header in Headers)
{
webRequest.Headers.Add(header.Key, header.Value);
}
if (!string.IsNullOrEmpty(PostData))
{
var RequestStream = new StreamWriter(webRequest.GetRequestStream());
RequestStream.Write(PostData);
RequestStream.Close();
}
if (!string.IsNullOrEmpty(body))
{
byte[] byteArray = Encoding.UTF8.GetBytes(body);
webRequest.ContentLength = byteArray.Length;
Stream dataStream = webRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
}
var ResponseStream = new StreamReader(webRequest.GetResponse().GetResponseStream());
string cookie = string.Empty;
CookieCollection allCookies = cookieJar.GetCookies(webRequest.RequestUri);
foreach (Cookie c in allCookies)
{
cookie = cookie + c.Name + "=" + c.Value+";";
}
cookie = cookie.Substring(0, cookie.LastIndexOf(';'));
var ResponseData = ResponseStream.ReadToEnd();
response.response=ResponseData.ToString();
response.cookie=cookie;
return response;
}
catch (WebException webException)
{
if (webException == null || webException.Response == null)
return null;
var responseStream = webException.Response.GetResponseStream() as MemoryStream;
if (responseStream == null)
return null;
var responseBytes = responseStream.ToArray();
var responseString = Encoding.UTF8.GetString(responseBytes);
response.response = responseString;
return response;
}
}
Whenever I am calling any api method I am sending token and cookie in header like below:
public string DownLoadDocument( string FilePath, string FileName, string token,string cookie)
{
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
HttpWebRequest webRequest;
webRequest = (HttpWebRequest)WebRequest.Create(URL);
webRequest.Method = "GET";
webRequest.ContentType = "application/octet-stream;charset=UTF-8";
webRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1";
webRequest.Headers.Add("Cookie", cookie);
webRequest.Headers.Add("Authentication", "Bearer "+token);
webRequest.Headers.Add("Content-Disposition", "attachment");
Stream responseReader = webRequest.GetResponse().GetResponseStream();
using (var fs = new FileStream(FilePath, FileMode.Create))
{
responseReader.CopyTo(fs);
}
}
catch (Exception ex)
{
throw;
}
return FilePath;
}
Following is the API Call i make using postman and get a ticket back in the response body (screenshot):
I am not able to get the ticket in a HttpWebRequest Response in C#. Please below see the small sample code:
C# code
HttpWebRequest Request = WebRequest.Create(strUrl) as HttpWebRequest;
Request.Method = "POST";
Request.Headers.Add("Authorization", "Basic <>");
//Request.ContentType = "application/form-data";
Request.KeepAlive = true;
string data = string.Format("username=" + UserName + "&password=" + Password);
byte[] dataStream = Encoding.UTF8.GetBytes(data);
Request.ContentLength = dataStream.Length;
using (Stream newStream = Request.GetRequestStream())
{
// Send the data.
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();
}
var Response = (HttpWebResponse)Request.GetResponse();
using (var stream = Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
if (Response.StatusCode != HttpStatusCode.OK)
throw new Exception("The request did not complete successfully and returned status code " + Response.StatusCode);
ResponseTicket strTicket= JsonConvert.DeserializeObject<ResponseTicket>(reader.ToString());
JsonConvert.DeserializeObject(Response.GetResponseStream().ToString());
MessageBox.Show(strTicket.Ticket);
}
Where as statuscode=200. But the content length is 0.
It is very difficult to find any meaning full help on CS10.5 API. I have checked there AppWorks platform but in vain. Would appreciate if someone can find the problem in the code, which apparently i can not see.
I don't know if this is still an issue for you. For me it was also, but figured it out:
public string LoginAsAdminAndRetrieveTicket(string userName, string passWord, string domain, string url)
{
var uri = $"http://{url}/otcs/llisapi.dll/api/v1/auth";
var request = new HttpRequestMessage();
request.Headers.Add("Connection", new[] { "Keep-Alive" });
request.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");
request.Headers.Add("Pragma", "no-cache");
request.RequestUri = new Uri(uri);
request.Method = HttpMethod.Post;
request.Content = new StringContent($"username={userName};password={passWord}", Encoding.UTF8, "application/x-www-form-urlencoded");
var httpClientHandler = new HttpClientHandler
{
Proxy = WebRequest.GetSystemWebProxy(),
UseProxy = true,
AllowAutoRedirect = true
};
using (var client = new HttpClient(httpClientHandler))
{
var response = client.SendAsync(request).Result;
string ticket;
var vals = response.Headers.TryGetValues("OTCSTicket", out IEnumerable<string> temp) ? temp : new List<string>();
if (vals.Any())
{
ticket = vals.First();
}
return response.Content.ReadAsStringAsync().Result;
}
}
I'm trying to use .net to put datapoints in OpenTSDB, using the HTTP /api/put API.
I've tried with httpclient, webRequest and HttpWebRequest. The outcome is always 400 - bad request: chunked request not supported.
I've tried my payload with an api tester (DHC) and works well.
I've tried to send a very small payload (even plain wrong, like "x") but the reply is always the same.
Here's one of my code instances:
public async static Task PutAsync(DataPoint dataPoint)
{
try
{
HttpWebRequest http = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:4242/api/put");
http.SendChunked = false;
http.Method = "POST";
http.ContentType = "application/json";
Encoding encoder = Encoding.UTF8;
byte[] data = encoder.GetBytes( dataPoint.ToJson() + Environment.NewLine);
http.Method = "POST";
http.ContentType = "application/json; charset=utf-8";
http.ContentLength = data.Length;
using (Stream stream = http.GetRequestStream())
{
stream.Write(data, 0, data.Length);
stream.Close();
}
WebResponse response = http.GetResponse();
var streamOutput = response.GetResponseStream();
StreamReader sr = new StreamReader(streamOutput);
string content = sr.ReadToEnd();
Console.WriteLine(content);
}
catch (WebException exc)
{
StreamReader reader = new StreamReader(exc.Response.GetResponseStream());
var content = reader.ReadToEnd();
}
return ;
}
where I explicitly set to false the SendChunked property.
note that other requests, like:
public static async Task<bool> Connect(Uri uri)
{
HttpWebRequest http = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:4242/api/version");
http.SendChunked = false;
http.Method = "GET";
// http.Headers.Clear();
//http.Headers.Add("Content-Type", "application/json");
http.ContentType = "application/json";
WebResponse response = http.GetResponse();
var stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
string content = sr.ReadToEnd();
Console.WriteLine(content);
return true;
}
work flawlessly.
I am sure I am doing something really wrong.
I'd like to to reimplement HTTP in Sockets from scratch.
I've found a solution I'd like to share here.
I've used wireshark to sniff my packets, and I've found that this header is added:
Expect: 100-continue\r\n
(see 8.2.3 of https://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html)
This is the culprit. I've read the post http://haacked.com/archive/2004/05/15/http-web-request-expect-100-continue.aspx/ by Phil Haack, and found that HttpWebRequest puts that header by default, unless you tell it to stop. In this article I've found that using ServicePointManager I can do just this.
Putting the following code on top of my method, when declaring the http object, makes it work very well, and solves my issue:
var uri = new Uri("http://127.0.0.1:4242/api/put");
var spm = ServicePointManager.FindServicePoint(uri);
spm.Expect100Continue = false;
HttpWebRequest http = (HttpWebRequest)WebRequest.Create(uri);
http.SendChunked = false;
So for example: https://www.website.com/index.php?action=get_products
This page/action has the following source code: <tr><td>Table</td></tr>
The index.php page has the following source code: <body>Hello</body>
When I use the following code I still get the index.php code and not the action page code:
Uri url = new Uri("https://www.website.com/index.php");
HttpWebRequest request = null;
ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
CookieContainer cookieJar = new CookieContainer();
request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = cookieJar;
request.Method = "GET";
HttpStatusCode responseStatus;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
responseStatus = response.StatusCode;
url = request.Address;
}
if (responseStatus == HttpStatusCode.OK)
{
UriBuilder urlBuilder = new UriBuilder(url);
urlBuilder.Path = urlBuilder.Path.Remove(urlBuilder.Path.LastIndexOf('/')) + "/j_security_check";
request = (HttpWebRequest)WebRequest.Create(urlBuilder.ToString());
request.Referer = url.ToString();
request.CookieContainer = cookieJar;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (Stream requestStream = request.GetRequestStream())
using (StreamWriter requestWriter = new StreamWriter(requestStream, Encoding.ASCII))
{
string postData = "?action=get_products";
requestWriter.Write(postData);
}
string responseContent = null;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream responseStream = response.GetResponseStream())
using (StreamReader responseReader = new StreamReader(responseStream))
{
responseContent = responseReader.ReadToEnd();
}
Console.WriteLine(responseContent);
}
else
{
Console.WriteLine("Client was unable to connect!");
}
I found the code above in another stackoverflow thread. The problem is I have to login first with username user and password pass. How do I get this done using C#?
I have successful connected to the login page, however, i'm not sure how to login and grab the file thats behind the login. Below is the code i'm using to make the connect.
private static bool bypassAllCertificateStuff(object sender, X509Certificate cert, X509Chain chain, System.Net.Security.SslPolicyErrors error)
{
return true;
}
public static void Processing()
{
string url = "https://app/templat";
HttpWebRequest request;
HttpWebResponse response;
CookieContainer cookies;
ServicePointManager.ServerCertificateValidationCallback =
System.Net.ServicePointManager.ServerCertificateValidationCallback =
((sender, certificate, chain, sslPolicyErrors) => true);
System.Net.ServicePointManager.ServerCertificateValidationCallback
= ((sender, cert, chain, errors) => cert.Subject.Contains("YourServerName"));
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(bypassAllCertificateStuff);
try
{
request = (HttpWebRequest)WebRequest.Create(url);
request.AllowAutoRedirect = false;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = new CookieContainer();
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
cookies = request.CookieContainer;
request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
String postData = "j_login=user&j_password=user&submit=Send";
byte[] data = System.Text.ASCIIEncoding.ASCII.GetBytes(postData);
request.ContentLength = data.Length;
//Stream stream = request.GetRequestStream();
//stream.Write(data, 0, data.Length);
request.CookieContainer = cookies;
//stream.Close();
StreamReader sr = new StreamReader(response.GetResponseStream());
string tmp = sr.ReadToEnd().Trim();
//response = (HttpWebResponse)request.GetResponse();
//WebClient wbClient = new WebClient();
//wbClient.DownloadFile("https://app/template/simple%2Screen.vm", #"C:\test.xls");
response.Close();
}
else
{
Console.WriteLine("Client was unable to connect!");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
I'm positive the download doesn't work and i'm sure String postData doesn't perform what intend it to.
Below is the code for the website login
<pre>
<form name=\"loginform\" method=\"post\" action=\"j_security_check\" onSubmit=\"javascript:fixFields();\">
<br>
<table border=\"0\" cellpadding=\"5\" cellspacing=\"0\" width=\"80%\">
<tr>
<td colspan=\"2\" align=\"center\" nowrap=\"nowrap\">
<div id=\"bannerDiv\" class=\"groupingBorder\" style=\"visibility:hidden;position:relative;background-color:#FFFFFF; overflow:auto;\">
</div>
</td>
</tr>
<tr>
<td class=\"contentrtanbld\" nowrap width=\"50%\">Name:</td>
<td class=\"contentltan\" nowrap width=\"50%\">
<input type=\"text\" name=\"j_username\" id=\"j_username\" value=\"\" class=\"authGroupWidth\" size=\"20\"></td>
</tr>
<tr>
<td class=\"contentrtanbld\" nowrap>Password:</td>
<td class=\"contentltan\" nowrap>
<input type=\"password\" name=\"j_password\" id=\"j_password\" value=\"\" class=\"authGroupWidth\" size=\"20\"></td>
</tr>
<tr>
</pre>
And the file I want to download is via this link
https://app/template/simple%2Screen.vm
I'm able to make the connection to the webpage but i'm unsure how to login and download the file.
Please see update to code. This is still not logging in and i'm not sure why.
string url = "https://mgr/app";
HttpWebRequest request;
HttpWebResponse response;
CookieContainer cookies = new CookieContainer();
ServicePointManager.ServerCertificateValidationCallback =
System.Net.ServicePointManager.ServerCertificateValidationCallback =
((sender, certificate, chain, sslPolicyErrors) => true);
System.Net.ServicePointManager.ServerCertificateValidationCallback
= ((sender, cert, chain, errors) => cert.Subject.Contains("YourServerName"));
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(bypassAllCertificateStuff);
try
{
string cookieHeader;
string formParams = string.Format("j_login={0}&j_password={1}", "user", "user");
request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
request.ContentLength = bytes.Length;
using (Stream os = request.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = request.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];
string pageSource;
string BehinPath = "https://mgr/app/action/store.VivolAction/eventsubmit_dopreparevivollist/ignored";
WebRequest getRequest = WebRequest.Create(BehinPath);
getRequest.Headers.Add("Cookie", cookieHeader);
WebResponse getResponse = getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
This is the new code, there is 1 cookie, however when i try the first post it never logs in.
Your code has the following problems that I can see:
Doesn't properly handle the cookie container. CookieContainer should be initialized and then passed to your HttpWebRequest, not the other way around.
Does not cleanup disposable objects. Failing to dispose an object can result in the object hanging around for quite a while before the garbage collector catches up with it.
Does not account for the form action. Your form action will cause a submit to a different location.
Unnecessarily performs the first operation as a POST. Use GET instead.
Does not set the referer when performing the POST operation.
Try the following code:
Uri url = new Uri("http://app/templat");
HttpWebRequest request = null;
// Uncomment the line below only if you need to accept an invalid certificate, i.e. a self-signed cert for testing.
// ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
CookieContainer cookieJar = new CookieContainer();
request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = cookieJar;
request.Method = "GET";
HttpStatusCode responseStatus;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
responseStatus = response.StatusCode;
url = request.Address;
}
if (responseStatus == HttpStatusCode.OK)
{
UriBuilder urlBuilder = new UriBuilder(url);
urlBuilder.Path = urlBuilder.Path.Remove(urlBuilder.Path.LastIndexOf('/')) + "/j_security_check";
request = (HttpWebRequest)WebRequest.Create(urlBuilder.ToString());
request.Referer = url.ToString();
request.CookieContainer = cookieJar;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (Stream requestStream = request.GetRequestStream())
using (StreamWriter requestWriter = new StreamWriter(requestStream, Encoding.ASCII))
{
string postData = "j_username=user&j_password=user&submit=Send";
requestWriter.Write(postData);
}
string responseContent = null;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream responseStream = response.GetResponseStream())
using (StreamReader responseReader = new StreamReader(responseStream))
{
responseContent = responseReader.ReadToEnd();
}
Console.WriteLine(responseContent);
}
else
{
Console.WriteLine("Client was unable to connect!");
}
Fist thing, you need to initiate the cookie container before the first request:
CookieContainer cookies = new CookieContainer();
then you need to pass it on each request(now you're just instantiating it again, thus losing all the cookies):
request.CookieContainer = cookies;
the response you're getting will fill the cookie container with the necessary cookies.
Furthermore, as I see you are already doing, you need to perform a series of Request/Response on the website and track the cookies. Use a tool like Fiddler to see what exactly how you need to formulate your POST strings to correctly login to the website.