Obtain a token from a POST request - c#

I'm trying to obtain a token from a POST request, but I'm not really sure how I'm supposed to read the response. I'm also not really sure how to put the username and password in the body of the message. I tried using httpWReq.Credentials = new NetworkCredential("myUsername","myPassword") but that wasn't working.
The documentation states:
Here is my code:
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(
"https://myportalURI.com/token");
string s = "user=myUserName,password=myPassword";
var data = Encoding.Default.GetBytes(s);
httpWReq.Method = "POST";
httpWReq.ContentType = "application/json";
httpWReq.ContentLength = data.Length;
var newStream = httpWReq.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();

Related

Bad Request(400) is alsways returned when I try to get access token from live.com

I already got the authorization code.
I try to get access token with the following code:
string requestUrl = "https://login.live.com/oauth20_token.srf";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string fields = string.Format("client_id={0}&redirect_uri={1}&client_secret={2}&code={3}&grant_type=authorization_code", clientId_, "https://login.live.com/oauth20_desktop.srf", clientSecret_, authorizationCode_);
var data = Encoding.ASCII.GetBytes(fields);
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
The last string always raises an WebException: Bad Request
Update: Just remove client_secret from fields and get the access token:
string fields = string.Format("client_id={0}&redirect_uri={1}&code={2}&grant_type=authorization_code", clientId_, "https://login.live.com/oauth20_desktop.srf", authorizationCode_);

scrape site after login

I'm trying to scrape a website that requires a login. Getting an error that I haven't received before, copied the code from another forum successfully in the past:
Exception Details: System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type.
with the code:
Stream newStream = http.GetRequestStream(); //open connection
Here's the entire code:
#{
var strUserId = "userName";
var strPassword = "password";
var url = "formSubmitLandingSite";
var url2 = "pageToScrape";
HttpWebRequest http = WebRequest.Create(url) as HttpWebRequest;
http.KeepAlive = true;
http.Method = "POST";
http.ContentType = "application/x-www-form-urlencoded";
string postData = "email=" + strUserId + "&password=" + strPassword;
byte[] dataBytes = UTF8Encoding.UTF8.GetBytes(postData);
http.ContentLength = dataBytes.Length;
using (Stream postStream = http.GetRequestStream())
{
postStream.Write(dataBytes, 0, dataBytes.Length);
}
HttpWebResponse httpResponse = http.GetResponse() as HttpWebResponse;
// Probably want to inspect the http.Headers here first
http = WebRequest.Create(url2) as HttpWebRequest;
http.CookieContainer = new CookieContainer();
http.CookieContainer.Add(httpResponse.Cookies);
HttpWebResponse httpResponse2 = http.GetResponse() as HttpWebResponse;
Stream newStream = http.GetRequestStream(); //open connection
newStream.Write(dataBytes, 0, dataBytes.Length); // Send the data.
newStream.Close();
string sourceCode;
HttpWebResponse getResponse = (HttpWebResponse)http.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
sourceCode = sr.ReadToEnd();
}
Response.Write(sourceCode);
}
You're creating a new request object here:
http = WebRequest.Create(url2) as HttpWebRequest;
Keep in mind that the default HTTP verb used is GET. Then you try to open the request stream here:
Stream newStream = http.GetRequestStream();
This method is used to enable writing data to the request's content. However, GET requests don't have content. As you do in the code above the error, you'll need to use a different HTTP verb. POST is most common for this, and is what you're using above:
http.Method = "POST";
So just use a POST request again. (Assuming, of course, that's what the server is expecting. In any event, if the server is expecting content then it's definitely not expecting a GET request.)

How to make a Post request from one website to another?

Lets say I have two websites, Website-A and Website-B.
Website-A receives a post request (From a third party website), I want to relay this request along with its data to website-B. I tried the below approach but it doesn't seems to navigate to the website B.
string newUrl = "http://localhost/WebSite-B/Test.aspx";
HttpRequest original = HttpContext.Current.Request;
HttpWebRequest newRequest = (HttpWebRequest)WebRequest.Create(newUrl);
newRequest.ContentType = original.ContentType;
newRequest.Method = original.HttpMethod;
newRequest.UserAgent = original.UserAgent;
byte[] originalStream;
using (var memoryStream = new MemoryStream())
{
original.InputStream.CopyTo(memoryStream);
originalStream = memoryStream.ToArray();
}
Stream reqStream = newRequest.GetRequestStream();
reqStream.Write(originalStream, 0, originalStream.Length);
reqStream.Close();
newRequest.CookieContainer = new CookieContainer();
newRequest.GetResponse();
The GetResponse() doesn't seem to open up or navigate to the requested page.
Please help me to pass on the POST request received by Website-A to Website-B.
I have answered a similar question in another web site. For your convinience here is a sample code:
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "now=" + strId;
postData += ("&random=" + random);
byte[] data = encoding.GetBytes(postData);
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(http://www.domain.com/controler/action);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
An alternative method to acomplish the same functionality can be found here

Internal server error 500 when I am trying to get all `groupid` from `ektron` in .net (c#)

My code:
HttpWebRequest httpWReq = (HttpWebRequest)System.Net.WebRequest.Create(domainUrl + "/Workarea/webservices/WebServiceAPI/User/User.asmx/GetAllUserGroups");
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "OrderBy=Id";
byte[] data = encoding.GetBytes(postData);
httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
httpWReq.ContentLength = data.Length;
using (Stream stream = httpWReq.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
getXmlValue1(responseString);
Tested the above piece of code at my end (Ektron V9),and it's working fine.
The issue may be with the ektron site that you are referring.
Check whether the Ektron website to which you make the POST request is accessible or not.

Getting error while fetching information from windows live server

I am trying to authenticate user through windows live account with following code.
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
WebRequest request = WebRequest.Create("https://oauth.live.com/token");
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
request.Method = "POST";
Stream resp = request.GetRequestStream();
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
var response = request.GetResponse();
But I am getting following error at last line.
The remote server returned an error: (400) Bad Request.
what should I do for this?
Your issue is probably because we do not send bytes on "application/x-www-form-urlencoded" post but a string. Also the GetRespose is not looks like the correct one. Your code must be something like:
// I do not know how you create the byteArray
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// but you need to send a string
string strRequest = Encoding.ASCII.GetString(byteArray);
WebRequest request = WebRequest.Create("https://oauth.live.com/token");
request.ContentType = "application/x-www-form-urlencoded";
// not the byte length, but the string
//request.ContentLength = byteArray.Length;
request.ContentLength = strRequest.Length;
request.Method = "POST";
using (StreamWriter streamOut = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII))
{
streamOut.Write(strRequest);
streamOut.Close();
}
string strResponse;
// get the response
using (StreamReader stIn = new StreamReader(request.GetResponse().GetResponseStream()))
{
strResponse = stIn.ReadToEnd();
stIn.Close();
}
// and here is the results
FullReturnLine = HttpContext.Current.Server.UrlDecode(strResponse);

Categories

Resources