C# (.NET), http web request (post method) with Aut

2019-09-14 21:32发布

问题:

I'm trying to press one button in site opskins with C# app. When I press on it in browser, fiddler give me next

I don't have enough experience for that, so I think I add excess headers, make stupid mistakes, etc...

My code:

string username = textBox2.Text;
string password = textBox3.Text;
string userData = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));

/*Add Auth Header*/
string referer = "https://opskins.com/?loc=shop_checkout";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(referer);

/*Cookie and spec. Headers*/
request.Headers.Add("Cookie", "Cookie string from Fiddler here");
request.Headers.Add("X-OP-UserID", "2484329");
request.Headers.Add("X-CSRF", "2kXrd2qBf4eFxW1O6tM2ye3DELn4SJzDH");

request.Headers.Add("Authorization", "Basic" + userData);
string fData = "action=buy&hidden_bal=0&total=" + textBox1.Text + "&accept_tos=1&type=2";
byte[] eData = Encoding.UTF8.GetBytes(fData);

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36";
request.ContentLength = eData.Length;

using (var stream = request.GetRequestStream())
{
stream.Write(eData, 0, eData.Length);
}  

When my app is running, fiddler give me

But still not working, what i must fix or add to my code? Someone can tell me easier way to press one button in my site (only C#) ?

回答1:

According to Fiddler, the url in your request constructor should be "https://opskins.com/ajax/shop_buy_item.php";

Try to use CookieContainer to stash your cookies and add each of your cookies you want to send in the request.

request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(new URI("https://opskins.com"), new Cookie(key, value);

Also add this header: request.Referer = referer

If that still doesn't work, I'd recommend adding the rest of the headers from the first Fiddler request into your web request.