Getting error while fetching information from windows live server - c#

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);

Related

Send an HTTP POST request with C#

I'm try to Send Data Using the WebRequest with POST But my problem is No data has be streamed to the server.
string user = textBox1.Text;
string password = textBox2.Text;
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "username" + user + "&password" + password;
byte[] data = encoding.GetBytes(postData);
WebRequest request = WebRequest.Create("http://localhost/s/test3.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
WebResponse response = request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr99 = new StreamReader(stream);
MessageBox.Show(sr99.ReadToEnd());
sr99.Close();
stream.Close();
here the result
It's because you need to assign your posted parameters with the = equal sign:
byte[] data = Encoding.ASCII.GetBytes(
$"username={user}&password={password}");
WebRequest request = WebRequest.Create("http://localhost/s/test3.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
string responseContent = null;
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader sr99 = new StreamReader(stream))
{
responseContent = sr99.ReadToEnd();
}
}
}
MessageBox.Show(responseContent);
See the username= and &password= in post data formatting.
You can test it on this fiddle.
Edit :
It seems that your PHP script has parameters named diffently than those used in your question.

Custom header not included in the http post request

Box.com's Enterprise User Provisioning API requires OAUTH2 token in the header of the request ("Authorization: Bearer faKE_toKEN_1234"). I've ran the code below against http://www.xhaus.com/headers, http://httpbin.org/post and http://www.cs.tut.fi/cgi-bin/run/~jkorpela/echo.cgi and observed packets with Microsoft Network Monitor and as far as I know my request header does not include the "Authorization" value I wish to include there.
Is the code below missing something (code or a point)?
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(API_URL);
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout=10000;
string postData = Parameters;
ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] byte1 = encoding.GetBytes (postData);
request.ContentLength = byte1.Length;
Stream reqStream = request.GetRequestStream();
reqStream.Write(byte1, 0, byte1.Length);
reqStream.Close();
//This is puzzling me, why can't I see this header anywere
//when debugging with packet monitor etc?
request.Headers.Add("Authorization: Bearer " + access_token);
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
Stream dataStream = response.GetResponseStream ();
StreamReader reader = new StreamReader (dataStream);
string txtResponse = reader.ReadToEnd ();
return txtResponse;
I think you need to set the header before you write the postData and close the request stream. This appeared to work for me:
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.xhaus.com/headers");
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 10000;
request.Headers.Add("Authorization: Bearer_faKE_toKEN_1234");
string postData = "postData";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byte1 = encoding.GetBytes(postData);
request.ContentLength = byte1.Length;
Stream reqStream = request.GetRequestStream();
reqStream.Write(byte1, 0, byte1.Length);
reqStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string txtResponse = reader.ReadToEnd();
Console.WriteLine(txtResponse);
Console.ReadKey();
}

Consume wcf service using HttpWebRequest c#

HttpWebRequest req = null;
HttpWebResponse res = null;
const string url = http://localhost/MyService/EService.svc/CreateMethod";
req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/json; charset=utf-8";
req.Headers.Add("App", "Application");
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] data = encoder.GetBytes("{ itemlist: 'sasfs' }");
req.ContentLength = data.Length;
res = (HttpWebResponse)req.GetResponse();
Stream responseStream = res.GetResponseStream();
var streamReader = new StreamReader(responseStream);
string txt = streamReader.ReadToEnd();
streamReader.Close();
streamReader.Dispose();
responseStream.Close();
responseStream.Dispose();
I have to use above code to consume service, but i am getting different errors-
1) You must provide a request body if you set ContentLength>0 ....
What is the code I am missing exactly here.
You missing few lines of code. You only setting ContentLength but you do not write content.
req.ContentLength = data.Length;
//Write request data(setting content of request)
Stream reqStream = req.GetRequestStream();
reqStream.Write(data, 0, data.Length);
reqStream.Close();
res = (HttpWebResponse)req.GetResponse();

Unable to consume POST method of OpenShift REST based API

I am trying to create application into OpenShift Red hat environment from my sample code which I have developed in C#.net.
string url =string.Format("https://openshift.redhat.com/broker/rest/domain/{0}/applications", cbDomains.Text);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Credentials = new NetworkCredential(USERNAME, PASSWORD);
string postData = "{\"name\": \"myapp\","
+ "\"cartridges\": [{"
+ "\"cartridge\": \"diy-0.1\"}],"
+ "\"scale\": false,"
+ "\"gear_size\": \"small\"}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded;";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
when I am executing above code I am getting following error:
The remote server returned an error: (422) Unprocessable Entity.
on this below line:
WebResponse response = request.GetResponse();
Please let me where I am doing wrong. Thanks in advance Jyoti

Can't get JSON POST response

I have this code:
WebRequest request = WebRequest.Create("https://getpocket.com/v3/oauth/request");
request.Proxy = WebRequest.DefaultWebProxy;
request.Credentials = System.Net.CredentialCache.DefaultCredentials; ;
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.Method = "POST";
string postData = "{\"consumer_key\":\"keyIsHere\",\"redirect_uri\":\"pickpocket:authorizationFinished\"}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/json; charset=utf-8";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
It returns code=12345456787blahblah instead of the JSON response: {"code":"12345456787blahblah"} and I can't figure out why. I got the POST request/response code from MSDN and the correct request data from the Pocket API
You need to add the X-Accept header:
request.Headers["X-Accept"] = "application/json";
From the API docs: "The X-Accept header indicates the format you would like to receive the response, the Pocket Authentication API supports two formats: application/x-www-form-urlencoded (DEFAULT) and application/json"

Categories

Resources