Rest API Post in RestSharp - c#

I was provided a snippet of code to make a call to a REST API and it works just fine, but i want to make the same call in RestSharp but cant quite figure it out the conversion.
Here is the code of the call that i want to convert to a restsharp call.
var request = (HttpWebRequest)WebRequest.Create("https://www.apisite.co.uk/api/GetUser");
var postData = "api_key=123&api_secret=456&response_type=json&user_id=user1234";
var data = Encoding.ASCII.GetBytes(postData);
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();
responseString gives me my response in json.
Any help would be appreciated.

var restClient = new RestClient("https://www.apisite.co.uk");
var restRequest = new RestRequest("api/GetUser", Method.POST);
restRequest.AddQueryParameter("api_key", "123");
restRequest.AddQueryParameter("api_secret", "456");
restRequest.AddQueryParameter("response_type", "json");
restRequest.AddQueryParameter("user_id", "user1234");
// response as a string
var restResponseString = restClient.Execute(restRequest).Content;
// response deserialized to an object/model
var restResponseDeserialized = restClient.Execute<object>(restRequest).Data;

Related

Convert HttpWebRequest to HttpClient with POST method

I try to convert HttpWebRequest to HttpClient but without success.
Can anybody help me?
It is my simple code with HttpWebRequest:
string url = "https://www.somesite.com/Service";
string postData = "text to send";
var data = Encoding.ASCII.GetBytes(postData);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
request.Proxy = null;
request.AllowAutoRedirect = false;
request.UserAgent = "Mozilla/5.0";
request.ContentType = "text/x-gwt-rpc; charset=UTF-8";
request.Headers.Add("Cookie", SetCookie);//get it after login
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseText = reader.ReadToEnd();
I think you can convert you HttpWebRequest based code to HttpClient based like this:
string url = "https://www.somesite.com/Service";
string postData = "text to send";
var data = Encoding.ASCII.GetBytes(postData);
var content = new ByteArrayContent(data);
using var httpHandler = new HttpClientHandler { UseCookies = false, AllowAutoRedirect = false };
using var client = new HttpClient(httpHandler);
client.DefaultRequestHeaders.Add("UserAgent","Mozilla/5.0");
client.DefaultRequestHeaders.Add("ContentType", "text/x-gwt-rpc; charset=UTF-8");
client.DefaultRequestHeaders.Add("Cookie", SetCookie);
using var requestMessage = new HttpRequestMessage(HttpMethod.Post, url) { Content = content };
var response = await client.SendAsync(requestMessage);
var responseText = await response.Content.ReadAsStringAsync();
Remarks:
Instead of writing the Request's Stream manually you can use the ByteArrayContent abstraction for this. (Related SO topic)
In order to set the cookie(s) manually you have to turn-off the default behaviour. You can do this via the HttpClientHandler's UseCookies. (Related SO topic)
To set the headers manually you can use the HttpClient's DefaultRequestHeaders (Related SO topic)
The counterpart of GetResponse is the SendAsync
Instead of reading the Response's Stream manually you can use the HttpContent's ReadAsStringAsync (Related SO topic)
UPDATE: Include OP's amended code
var content = new StringContent(postData, Encoding.UTF8, "text/x-gwt-rpc");
So, instead of ByteArrayContent StringContent is being used.

How can I Post data using HttpWebRequest?

I have this HttpWebRequest:
var request = HttpWebRequest.Create("http://example.com/api/Phrase/GetJDTO");
request.ContentType = "application/json";
request.Method = "POST";
But I need to add a payload to the body of the request like this:
Jlpt = 2
Can someone help and tell me how I can add data to the POST ?
You can do by this
var request = HttpWebRequest.Create("http://example.com/api/Phrase/GetJDTO");
var postData = "Jlpt = 2";
var data = Encoding.ASCII.GetBytes(postData);
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();
but I suggest you use HttpClient rather than HttpWebRequest in this case
if (data != null)
{
request.ContentType = "application/json";
using (var stream = new StreamWriter(request.GetRequestStream()))
{
var serialized = JsonConvert.SerializeObject(data);
stream.Write(serialized);
}
}
else
{
request.ContentLength = 0;
}
where data is any object you want to send

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