How to Call asmx service without adding service reference in C#.Net - c#

I am working on calling asmx webservice method without adding service reference as asmx doesn't provide wsdl. I can access asmx service from fiddler as well as from postman. It works fine. However when I try to call it from my C# code it throws 403 forbidden exception.
Below is my c# code.
internal class Class3
{
string _soapEnvelope =
#"<soap:Envelope
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns:xsd='http://www.w3.org/2001/XMLSchema'
xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>
<soap:Body></soap:Body></soap:Envelope>";
private string CreateSoapEnvelope()
{
Dictionary<string, string> Params = new Dictionary<string, string>();
Params.Add("aId", "11"); // Add parameterName & Value to dictionary
Params.Add("cId", "22");
Params.Add("lId", "20");
string MethodCall = "<" + "GetSettings" + #" xmlns=""http://tempuri.org/"">";
string StrParameters = string.Empty;
foreach (var param in Params)
{
StrParameters += string.Format("<{0}>{1}</{0}>", param.Key, param.Value);
}
MethodCall = MethodCall + StrParameters + "</" + "GetSettings" + ">";
StringBuilder sb = new StringBuilder(_soapEnvelope);
sb.Insert(sb.ToString().IndexOf("</soap:Body>"), MethodCall);
return sb.ToString();
}
private HttpWebRequest CreateWebRequest()
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("sample.asmx");
webRequest.Headers.Add("SOAPAction", "\"http://tempuri.org/" + "GetSettings" + "\"");
webRequest.Headers.Add("To", "sample.asmx");
webRequest.Credentials = CredentialCache.DefaultCredentials;
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9";
webRequest.Host = "sample.com";
webRequest.Headers.Set(HttpRequestHeader.CacheControl, "max-age=0");
webRequest.Headers.Add("Upgrade-Insecure-Requests: 1");
webRequest.Headers.Add("Origin", "null");
webRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
webRequest.Headers.Add("Accept-Language", "en-US,en;q=0.9,zh-CN;q=0.8,zh-TW;q=0.7,zh;q=0.6");
webRequest.Method = "POST";
return webRequest;
}
public string InvokeService()
{
try
{
WebResponse response = null;
string strResponse = "";
//Create the request
HttpWebRequest req = this.CreateWebRequest();
//write the soap envelope to request stream
using (Stream stm = req.GetRequestStream())
{
using (StreamWriter stmw = new StreamWriter(stm))
{
stmw.Write(this.CreateSoapEnvelope());
}
}
//get the response from the web service
response = req.GetResponse();
Stream str = response.GetResponseStream();
StreamReader sr = new StreamReader(str);
strResponse = sr.ReadToEnd();
return HttpUtility.HtmlDecode(strResponse);
}
catch (Exception ex)
{
return "";
}
}
}
internal class Program
{
static void Main(string[] args)
{
new Class3().InvokeService();
}
}
Tried adding below headers as well but it doesnt make any difference.
webRequest.ContentLength = 600000;
webRequest.ProtocolVersion = HttpVersion.Version11;
webRequest.KeepAlive = false;
webRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36";
I am using VS2022 - Console Application with .Net Framework 4.6.2
Can somebody please help me understand what am I doing wrong here.

after lot of research I got to know that the way I am passing parameters were incorrect. Below is the simple and correct version of doing same. Its working now
string remoteUrl = "service.asmx";
string poststring = "aId=11&cId=22&lId=20";
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(remoteUrl);
httpRequest.Host = "host.com";
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.5195.127 Safari/537.36";
// Convert the post string to a byte array
byte[] bytedata = System.Text.Encoding.UTF8.GetBytes(poststring);
httpRequest.ContentLength = bytedata.Length;
// Create the stream
Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(bytedata, 0, bytedata.Length);
requestStream.Close();
// Get the response from remote server
HttpWebResponse httpWebResponse = (HttpWebResponse)httpRequest.GetResponse();
Stream responseStream = httpWebResponse.GetResponseStream();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
using (StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
sb.Append(line);
}
}
string data = sb.ToString();

Related

Error submitting login form to external website through c#

I'm currently trying to login to a website and submit a form once logged into the website.
I've tried looking through all the input fields and adding it to the code but still no luck.
The website I'm trying to login to is http://sythe.org/login/
Here's what I currently have:
string formUrl = "http://www.sythe.org/login/";
string formParams = string.Format("login={0}&password={1}&_xfToken={2}&register={3}&remember={4}&cookie_check={5}&redirect={6}", "", "", "", "0", "1", "1", "https://sythe.org");
string cookieHeader;
WebRequest req = WebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];
string pageSource;
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
Console.WriteLine(pageSource);
Thanks guys.
You can try this code which is generated using the C# plugin for Fiddler:
private void MakeRequests()
{
HttpWebResponse response;
if (Request_www_sythe_org(out response))
{
response.Close();
}
}
private bool Request_www_sythe_org(out HttpWebResponse response)
{
response = null;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.sythe.org/login/login");
request.KeepAlive = true;
request.Headers.Set(HttpRequestHeader.CacheControl, "max-age=0");
request.Headers.Add("Origin", #"https://www.sythe.org");
request.Headers.Add("Upgrade-Insecure-Requests", #"1");
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3";
request.Referer = "https://www.sythe.org/";
request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate, br");
request.Headers.Set(HttpRequestHeader.AcceptLanguage, "en-GB,en-US;q=0.9,en;q=0.8");
request.Headers.Set(HttpRequestHeader.Cookie, #"__cfduid=de8826b5a5df064d6f2ccf2d0952ce52d1554285418; _ga=GA1.2.1744286790.1554285420; _gid=GA1.2.1835584013.1554285420; G_ENABLED_IDPS=google; sythe_bug_token=c0FFSCNAJio4MzJnZWEjWXlaV1NCempSdWFrUzRnUHVZUXJKOENicnkwSmZFTXROR1M3MDhUR1ovWTFIVmlvRFZaaVN2MjFHRWtaM2JhT0N1bTJHbEdGSG5VY1dUNjdmVGNZd1RoekNmTmgzaHB4T29OTTZkNytJQWh3cDdjeWlndWpidkJFY0NiRXF4b1ljSVJhN2VGVVd2eEsvK2hrak1pclhvYjRFeWRhT09UUU5seXZDUVlETDlYWUUyazZGajRub3VWV0k5aVhkVVJiWUtxcFRuaTljRElnWEVKd2o4T3ZSZlRheFEzRWRzekgxSXN4d0doMS9YRFR6L1d0OGRONUVLcDZHUEN3eVFRWEQ%3D; _gat=1; xf_session=63943f38ebba0827a4208d363cae5dcb");
request.Headers.Add("AlexaToolbar-ALX_NS_PH", #"AlexaToolbar/alx-4.0.3");
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;
string body = #"login=testtest%40testtest.testtest&register=0&password=testtesttesttest&remember=1&cookie_check=1&redirect=%2F&_xfToken=";
byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(body);
request.ContentLength = postBytes.Length;
Stream stream = request.GetRequestStream();
stream.Write(postBytes, 0, postBytes.Length);
stream.Close();
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError) response = (HttpWebResponse)e.Response;
else return false;
}
catch (Exception)
{
if(response != null) response.Close();
return false;
}
return true;
}
try to replace string formUrl = "http://www.sythe.org/login/"; to string formUrl = "http://www.sythe.org/login/login";

How to get request with JSESSIONID c#?

I've a problem with a C# HTTP GET request.
I send two requests to server:
The first request returns the value of JSESSIONID and it's work:
private string GetSessionId(){
{
string id = null;
try
{
var webRequest = WebRequest.Create("http://www.xxxxxxxxxxxxxxx.it/home") as HttpWebRequest;
var response = "";
webRequest.Date = DateTime.UtcNow;
webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";
webRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
webRequest.Headers.Add("Accept-Language", "it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7,de-DE;q=0.6,de;q=0.5");
webRequest.Connection = "keep-alive";
webRequest.Headers.Add("Cache-Control", "max-age=0");
webRequest.Host = "www.xxxxxxxxxxxxxxxx.it";
webRequest.Headers.Add("Upgrade-Insecure-Requests", "1");
webRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36";
if (webRequest != null)
{
webRequest.Method = "GET";
using (WebResponse resp = webRequest.GetResponse())
{
using (Stream s = resp.GetResponseStream())
{
using (StreamReader sr = new StreamReader(s))
{
id = resp.Headers["Set-Cookie"];
response = sr.ReadToEnd();
Console.WriteLine("Response1> " + resp.Headers);
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return id;
}
The second request should return the server response to my search but it return an error "302 Moved Temporarily" or "Attention the session has expired".
private void RequestFromServer(string url)
{
string session = GetSessionId().Split(';')[0];
Console.WriteLine("Session> {0}",session);
try
{
HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest;
var response = "";
if (webRequest != null)
{
Uri target = new Uri(url);
webRequest.Method = "GET";
webRequest.Timeout = 20000;
webRequest.Date = DateTime.UtcNow;
webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";
webRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
webRequest.Headers.Add("Accept-Language", "it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7,de-DE;q=0.6,de;q=0.5");
webRequest.Headers.Add("Cache-Control", "max-age=0");
webRequest.Connection = "keep-alive";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Headers.Add("Cookie", session);
webRequest.Host = "www.xxxxxxxxxxxxxx.it";
webRequest.Headers.Add("Origin", "http://www.xxxxxxxxxxxx.it");
webRequest.Referer = "http://www.xxxxxxxxxxxxxxxx.it/ricerca/atto/contratti/originario?reset=true&normativi=false";
webRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36";
webRequest.Headers.Add("Upgrade-Insecure-Requests", "1");
var res = webRequest.GetResponse();
using (Stream s = res.GetResponseStream())
{
using (StreamReader sr = new StreamReader(s))
{
response = sr.ReadToEnd();
Console.Write(res.Headers);
Console.WriteLine(response);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Can someone help me with this problem?
What you probably need here is a CookieContainer. Instead of
webRequest.Headers.Add("Cookie", session);
you should do something like
webRequest.CookieContainer = new CookieContainer();
Cookie cookie = new new Cookie("JSESSIONID", yourSessionIdHere);
// adjust domain accordingly
cookie.Domain = "www.xxxxxxxxxxxxxxx.it";
httpRequest.CookieContainer.Add(cookie);
Code is untested.
The MSDN site also states:
For security reasons, cookies are disabled by default. If you want to use cookies, use the CookieContainer property to enable cookies.
That means in order to use cookies you have to set the CookieContainer explicitly.

httpWebRequest Json POST to Mojang Server is returning 403

I'm trying to make a json POST to the Mojang authentification server using a HttpWebRequest in C#.
I checked the headers with a Chrome addon and added them.
Below is my code, but I keep getting a 403 forbidden.
I got it working with a TcpClient but I need to do it with a HttpWebRequest as it accepts proxies.
Does someone now how to fix this?
public void test(string username, string password) {
try {
ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(ValidateRemoteCertificate);
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
string json = "{\"agent\":{\"name\":\"Minecraft\",\"version\":1},\"username\":\"" + username + "\",\"password\":\"" + password + "\",\"clientToken\":\"6c9d237d-8fbf-44ef-b46b-0b8a854bf391\"}";
var httpWebRequest = (HttpWebRequest) WebRequest.Create("https://authserver.mojang.com/authenticate");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.ContentLength = json.Length;
httpWebRequest.Host = "authserver.mojang.com";
httpWebRequest.Credentials = CredentialCache.DefaultCredentials;
httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36";
httpWebRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
httpWebRequest.Referer = "https://authserver.mojang.com/";
httpWebRequest.Headers.Add("Accept-Language", "de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4");
httpWebRequest.Headers.Add("Accept-Encoding", "gzip, deflate, sdch, br");
using(var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) {
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse();
using(var streamReader = new StreamReader(httpResponse.GetResponseStream())) {
var result = streamReader.ReadToEnd();
MessageBox.Show(result);
streamReader.Close();
}
} catch (Exception error) {
MessageBox.Show(error.ToString());
}
}

Multi-webrequests & WebClient

I'm trying to the html information on a certain a website so I can parse out the info for our database. The problem is that the second & third responseFromServer info comes back the same. However, when I follow the links on inside a real web browser, I get the right information (correct page).
I'm thinking that each WebRequest is basically opening a 'new' instance of the web and what I want it to do is use the same instance.
Is there a way to specify (using a WebClient?) so that each request is contained in the 'same browser' (for lack of a better term)
static void CountyInfo(string Address)
{
WebClient webClient = new WebClient();
webClient.Headers.Add("Cache-Control: private");
webClient.Headers.Add("Content-Type: text/html; charset=utf-8");
webClient.Headers.Add("Server: Microsoft-IIS/6.0");
webClient.Headers.Add("X-AspNet-Version: 4.0.30319");
webClient.Headers.Add("X-Powered-By: ASP.NET");
webClient.Headers.Add("X-UA-Compatible: IE=8, IE=9, IE=10, IE=11");
Address = Address.Replace(" ", "+");
string url1 = "http://mcassessor.maricopa.gov/?s=" + Address;
WebRequest request1 = WebRequest.Create(url1);
WebResponse response1 = request1.GetResponse();
//Stream dataStream1 = response1.GetResponseStream();
Stream dataStream1 = webClient.OpenRead(url1);
StreamReader reader1 = new StreamReader(dataStream1);
string responseFromServer1 = reader1.ReadToEnd();
string ParcelNum = getBetween(responseFromServer1, "http://treasurer.maricopa.gov/parcels/default.asp?Parcel=", "target=");
ParcelNum = new String(ParcelNum.Where(Char.IsDigit).ToArray());
//reader1.Close();
//response1.Close();
//NEW GET request
string url2 = "http://treasurer.maricopa.gov/parcels/default.asp?Parcel=" + ParcelNum;
WebRequest request2 = WebRequest.Create(url2);
WebResponse response2 = request2.GetResponse();
//Stream dataStream2 = response2.GetResponseStream();
Stream dataStream2 = webClient.OpenRead(url2);
StreamReader reader2 = new StreamReader(dataStream2);
string responseFromServer2 = reader2.ReadToEnd();
//reader2.Close();
//response2.Close();
//NEW GET request
string url3 = "http://treasurer.maricopa.gov/Parcel/" + "TaxDetails.aspx?taxyear=2013";
WebRequest request3 = WebRequest.Create(url3);
WebResponse response3 = request3.GetResponse();
//Stream dataStream3 = response3.GetResponseStream();
Stream dataStream3 = webClient.OpenRead(url3);
StreamReader reader3 = new StreamReader(dataStream3);
string responseFromServer3 = reader3.ReadToEnd();
reader3.Close();
response3.Close();
}
EDIT: just saw this. request1 gives me the correct page (the query results page) but request 2 and 3 return me back to the "Home Page" of the website. Even though i am passing in url2 and url3 into the requests2 & 3 respectively.
You need to manage the cookies. Get the cookies served by the web server and pass them back on the next request.
Sorry about the long code post, but this is how i got it working. Let me know if you can condense it any.
static public CookieContainer cookieJar;
static void Main(string[] args)
{
string ControlNumber = "######";
GetOrderInfo newOrder = new GetOrderInfo(ControlNumber);
obtainCookies();
MARICOPAcounty(newOrder.OrderAddress);
}
static void obtainCookies()
{
string postData = "http://mcassessor.maricopa.gov/";
CookieContainer tempCookies = new CookieContainer();
UTF8Encoding encoding = new UTF8Encoding();
byte[] byteData = encoding.GetBytes(postData);
HttpWebRequest postReq = (HttpWebRequest)WebRequest.Create("http://mcassessor.maricopa.gov/");
postReq.Method = "POST";
postReq.KeepAlive = true;
Cookie chocoChip = new Cookie("_ga", "GA1.2.1813386723.1386802842") { Domain = "http://mcassessor.maricopa.gov/" };
postReq.CookieContainer = new CookieContainer();
postReq.CookieContainer.Add(chocoChip);
postReq.ContentType = "text/html; charset=utf-8";
postReq.Referer = "http://mcassessor.maricopa.gov/";
postReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; MAM3; rv:11.0) like Gecko";
postReq.ContentLength = byteData.Length;
Stream postReqStream = postReq.GetRequestStream();
postReqStream.Write(byteData, 0, byteData.Length);
postReqStream.Close();
HttpWebResponse postResponse;
postResponse = (HttpWebResponse)postReq.GetResponse();
postResponse.Cookies.Add(chocoChip);
StreamReader postReqReader = new StreamReader(postResponse.GetResponseStream());
tempCookies.Add(chocoChip);
cookieJar = tempCookies;
string soureCode = postReqReader.ReadToEnd();
if (postReq != null)
{
Console.WriteLine("\r\n\r\n postResponse COOKIES");
Console.WriteLine(postResponse.Cookies[0]);
Console.WriteLine("\r\n\r\n postReq Headers");
Console.WriteLine(postReq.Headers.ToString());
Console.WriteLine("\r\n\r\n postResponse Headers");
Console.Write("\t" + postResponse.Headers);
}
}
public static string MARICOPAcounty(string Address)
{
//-------------------------------------------------------------------------------------------------------------------------------//
//-------------------------------------------------------------------------------------------------------------------------------//
Address = Address.Replace(" ", "+");
string url1 = "http://mcassessor.maricopa.gov/?s=" + Address;
HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create(url1);
request1.CookieContainer = cookieJar;
request1.Method = "GET";
request1.Accept = "text/html, application/xhtml+xml, */*";
request1.Headers.Add("Accept-Language: en-US");
request1.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; MAM3; rv:11.0) like Gecko";
request1.Headers.Add("Accept-Enconding: gzip, deflate");
HttpWebResponse response1 = (HttpWebResponse)request1.GetResponse();
StreamReader sr1 = new StreamReader(response1.GetResponseStream());
string sourceCode1 = sr1.ReadToEnd();
string ParcelNum = getBetween(sourceCode1, "http://treasurer.maricopa.gov/parcels/default.asp?Parcel=", "target=");
ParcelNum = new String(ParcelNum.Where(Char.IsDigit).ToArray());
if (response1 != null)
{
Console.WriteLine("\r\n\r\n request1 Headers");
Console.WriteLine(request1.Headers.ToString());
Console.WriteLine("\r\n\r\nresponse1 Headers");
Console.Write("\t" + response1.Headers);
}
sr1.Close();
response1.Close();
//-------------------------------------------------------------------------------------------------------------------------------//
//-------------------------------------------------------------------------------------------------------------------------------//
//NEW GET request
string url2 = "http://treasurer.maricopa.gov/parcels/default.asp?Parcel=50423370"; //+ ParcelNum;
HttpWebRequest request2 = (HttpWebRequest)WebRequest.Create(url2);
request2.CookieContainer = cookieJar;
request2.Method = "GET";
request2.Accept = "text/html, application/xhtml+xml, */*";
request2.Headers.Add("Accept-Language: en-US");
request2.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; MAM3; rv:11.0) like Gecko";
request2.Headers.Add("Accept-Encoding: gzip, deflate");
request2.Referer = url1;
HttpWebResponse response2 = (HttpWebResponse)request2.GetResponse();
StreamReader sr2 = new StreamReader(response2.GetResponseStream());
string sourceCode2 = sr2.ReadToEnd();
if (response2 != null)
{
Console.WriteLine("\r\n\r\nrrequest2 Headers");
Console.WriteLine(request2.Headers);
Console.WriteLine(request2.CookieContainer);
Console.WriteLine("\r\n\r\nresponse2 Headers");
Console.Write("\t" + response2.Headers);
}
sr2.Close();
response2.Close();
//-------------------------------------------------------------------------------------------------------------------------------//
//-------------------------------------------------------------------------------------------------------------------------------//
//new GET request
string url3 = "http://treasurer.maricopa.gov/Parcel/TaxDetails.aspx?taxyear=2013";
HttpWebRequest request3 = (HttpWebRequest)WebRequest.Create(url3);
request3.CookieContainer = cookieJar;
request3.Method = "GET";
request3.Accept = "text/html, application/xhtml+xml, */*";
request3.Headers.Add("Accept-Language: en-US");
request3.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; MAM3; rv:11.0) like Gecko";
request3.Headers.Add("Accept-Encoding: gzip, deflate");
request3.Referer = url2;
HttpWebResponse response3 = (HttpWebResponse)request3.GetResponse();
StreamReader sr3 = new StreamReader(response3.GetResponseStream());
string sourceCode3 = sr3.ReadToEnd();
if (response3 != null)
{
Console.WriteLine("\r\n\r\nrrequest3 Headers");
Console.WriteLine(request3.Headers);
Console.WriteLine("\r\n\r\nresponse3 Headers");
Console.Write("\t" + response3.Headers);
}
sr3.Close();
response3.Close();
return sourceCode3;
}

Error 403 with email checking program POST C#

I have been trying to figure out why this post method isn't going through. I've been using Fiddler, and have been working on this for hours now. If someone could help that would be great.
private string getemail(string user, string pass)
{
var cookies = new CookieContainer();
var getRequest = (HttpWebRequest)WebRequest.Create("http://account.mojang.com/migrate");
cookies = (getRequest as HttpWebRequest).CookieContainer;
string[] tok = ReadResponse(getRequest).Split(new string[] { "name=\"authenticityToken\" value=\"" }, StringSplitOptions.None);
string[] toke = tok[1].Split('"');
string token = toke[0];
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://account.mojang.com/migrate/check");
request.CookieContainer = cookies;
request.Method = "POST";
request.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3");
request.Headers.Add("Accept-Encoding: gzip,deflate,sdch");
request.Headers.Add("Accept-Language: en-US,en;q=0.8");
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31";
request.ContentType = "text/plain";
using (var requestStream = request.GetRequestStream())
{
using (var writer = new StreamWriter(requestStream))
{
writer.Write("authenticityToken=" + token + "&mcusername=" + user + "&password=" + pass);
}
}
using (var responseStream = request.GetResponse().GetResponseStream())
{
using (var reader = new StreamReader(responseStream))
{
var result = reader.ReadToEnd();
return result;
}
}
}
Close your StreamWriter after writing content into request stream.
using (var writer = new StreamWriter(requestStream))
{
writer.Write("authenticityToken=" + token + "&mcusername=" + user + "&password=" + pass);
writer.Close();
}

Categories