Post with parameters using HttpWebRequest in C# - c#

Having the following code:
var request = HttpWebRequest.Create("https://api.channeladvisor.com/oauth2/token");
request.ContentType = "text/html";
request.Method = "POST";
request.Headers.Add("cache-control","no-cache");
request.Headers.Add("Authorization", "Basic " + Base64Translator.ToBase64(System.Text.Encoding.ASCII, devKey+":"+sharedSecret));
string postData = " grant_type=refresh_token&refresh_token=a12SL1bHhJwerxM2NFth2efZw0yIW7462kAhR43UCJA";
var data = Encoding.ASCII.GetBytes(postData);
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
What's wrong? I can't do the request but I can using external programs like Postman. Do you see anything wrong in the header?
Error: "The remote server returned an error: (400) Bad Request."
Thanks!

Your content type should be application/x-www-form-urlencoded.
request.ContentType = "application/x-www-form-urlencoded";

Related

Error 400 with YouTube API and C#?

I am trying to update the title to a video, with an authorized put in C#:
string postUrl = "https://www.googleapis.com/youtube/v3/videos?part=snippet&access_token=" + this.access_token;
string postData = "id=" + this.videoID +
"&snippet[title]=" + Uri.EscapeDataString(status.Text) +
"&snippet[categoryId]=20";
byte[] postByte = Encoding.UTF8.GetBytes(postData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);
request.Method = "PUT";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postByte.Length;
request.Timeout = 15000;
try
{
Stream putStream = request.GetRequestStream();
putStream.Write(postByte, 0, postByte.Length);
putStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
catch (WebException err)
{
MessageBox.Show(err.Message);
}
The above code shows the following error:
The remote server returned an error: (400) Bad Request.
What am I doing wrong?
I figured it out. This particular endpoint needs a json responce, instead of a x-www-form-urlencoded response.

(400) Bad Request, can't get response (Custom minecraft launcher)

I just can't seem to be able to post a JSON to the webpage https://authserver.mojang.com/authenticate and get a response.
when I post the JSON it just says
The remote server returned an error: (400) Bad Request
I've gone through many different scripts by others and created my own by converting the Java code to C#. Anyway, here's the code that has worked the best so far.
string authserver = "https://authserver.mojang.com/authenticate";
byte[] rawData = fs.GetBytes(**[JSON]**);
WebRequest request = WebRequest.Create(authserver);
request.ContentType = "application/json";
request.Method = "POST";
//request.ContentLength = rawData.LongLength;
WebResponse connection = request.GetResponse();
connection.ContentType = "application/json";
connection.ContentLength = rawData.LongLength;
Stream stream = connection.GetResponseStream();
stream.Write(rawData, 0, rawData.Length);
stream.Flush();
byte[] rawVerification = new byte[10000];
int count = stream.Read(rawVerification, 0, 10000);
Edit:
is it possible to do this code with webclient?
Edit:
it had an invalid input, the json didn't have the correct data needed
try this:
WebRequest request = WebRequest.Create (authserver);
request.Method = "POST";
string postData = "YourJSON";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
request.ContentType = "application/json";
request.ContentLength = byteArray.Length;
using(Stream s = request.GetRequestStream ()){
s.Write (byteArray, 0, byteArray.Length);
}
WebResponse response = request.GetResponse ();
using(var dataStream = response.GetResponseStream ()){
using(StreamReader reader = new StreamReader (dataStream)){
string responseFromServer = reader.ReadToEnd ();
}
}
response.Close();
Essentially You shouldn't call getResponse() before you submit your data

Web Request Not Returning Anything

I'm trying to login to this website here: https://freebitco.in/
So I set up a web request like so:
var request = (HttpWebRequest)WebRequest.Create("https://freebitco.in");
var postdata = "op=login&btc_address=BTCADDRESS&password=PASSWORD";
var data = Encoding.ASCII.GetBytes(postdata);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length; //1PkhThc9hCXpdvcThtwX3SzbfmTzDFxL1h:bigken <= BTC Login
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
MessageBox.Show(responseString);
The messagebox returns to me nothing though, blank. I'm not sure why this is happening so I was hoping someone could shed some light on this? I've also tried using a Web Client, and it gave me the same result. Thank you guys.
EDIT: Here's the Fiddler Raw data: http://pastebin.com/WUEvq6D5
Edit 2: Tried encoding the POST data and now it returns the login page
Updated Code:
var request = (HttpWebRequest)WebRequest.Create("https://freebitco.in");
var postdata = "op=login&btc_address=ADDRESS&password=PASS";
var encoded_data = HttpUtility.UrlEncode(postdata);
var data = Encoding.ASCII.GetBytes(encoded_data);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

How to use WebRequest in c#

I'am trying to use example api call in below link please check link
http://sendloop.com/help/article/api-001/getting-started
My account is "code5" so i tried 2 codes to get systemDate.
1. Code
var request = WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
request.ContentType = "application/json; charset=utf-8";
string text;
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
2.Code
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";
But i don't know that i use correctly api by above codes ?
When i use above codes i don't see any data or anything.
How can i get and post api to Sendloop.And how can i use api by using WebRequest ?
I will use api first time in .net so
any help will be appreciated.
Thanks.
It looks like you need to post your API key to the endpoint when making requests. Otherwise, you will not be authenticated and it will return an empty response.
To send a POST request, you will need to do something like this:
var request = WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
request.ContentType = "application/json; charset=utf-8";
string postData = "APIKey=xxxx-xxxxx-xxxxx-xxxxx-xxxxx";
request.Method = "POST";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
request.ContentLength = data.Length;
Stream newStream = request.GetRequestStream(); //open connection
newStream.Write(data, 0, data.Length); // Send the data.
newStream.Close();
string text;
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
string userAuthenticationURI =
"https://maps.googleapis.com/maps/api/distancematrix/json?origins="+ originZip +
"&destinations="+ DestinationZip + "&units=imperial&language=en-
EN&sensor=false&key=Your API Key";
if (!string.IsNullOrEmpty(userAuthenticationURI))
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(userAuthenticationURI);
request.Method = "GET";
request.ContentType = "application/json";
WebResponse response = request.GetResponse();
var responseString = new
StreamReader(response.GetResponseStream()).ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject(responseString);
}

disqus API missing required parameter: grant_type

I am trying to retrieve an access_token through the disqus API.
This is my url:
https://disqus.com/api/oauth/2.0/access_token/?client_id=cvwNO7HaRwgYDq9anat8j7uzowJ8HBEz8gH7mUnmMhC0BKZZTkObc5d7o242liNG&grant_type=authorization_code&client_secret=Hrrgy1ZLcLN0qjmZhzXR2owET8cGazcbcGNxTlsWEJYiNfc3JcQLbKx2PYW6yNU7&redirect_uri=http://www.aftenposten.no&code=PM6QYwUJ
i'm getting an error: missing required parameter: grant_type
i'm using the following code to get the response:
HttpWebRequest request = HttpWebRequest.CreateHttp(uri);
request.Method = "POST";
request.BeginGetResponse(new AsyncCallback(getAccessTokenResponse), request);
You need to pass the form data in the request body and not as url parameters. Give this a try:
var uri = "https://disqus.com/api/oauth/2.0/access_token/"
HttpWebRequest request = HttpWebRequest.CreateHttp(uri);
var data = "client_id=[your client id]"
data += "&grant_type=authorization_code"
data += "&client_secret=[your client secret]"
data += "&redirect_uri=http://www.aftenposten.no&code=PM6QYwUJ"
var postData = Encoding.ASCII.GetBytes(data);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

Categories