What the difference between this Post webrequest and similar request in Postman? - c#

I want to make Post request to "https://sslecal2.forexprostools.com/ajax.php". So there is my code:
string URI = "https://sslecal2.forexprostools.com/ajax.php";
string requestBody = String.Format("{{\"dateFrom\": \"{0}\", \"dateTo\": \"{1}\", \"timeZone\": {2}, \"action\": \"{3}\"}}",
"2018-12-24", "2018-12-24", 18, "filter"); //json format
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URI); //make request
request.Method = "POST";
request.UserAgent = "";
request.Headers.Add("X-Requested-With", "XMLHttpRequest");
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(requestBody); //write your request payload
}
WebResponse response = request.GetResponse();
string jsonData = String.Empty;
using (var reader = new StreamReader(response.GetResponseStream()))
{
jsonData = reader.ReadToEnd();
}
response.Close();
I made something not correct in "requestBody" in string " string requestBody = String.Format("{{\"dateFrom\"..." because I get 200 and empty html answer.
And I attach the screens of the same request in postman with html code in answer. This request in postman processes well.
What the difference between this Post webrequest and request in Postman?

With postman you posting different format data. To get same thing in code you need to change request body format and set content type of request:
string URI = "https://sslecal2.forexprostools.com/ajax.php";
string requestBody = String.Format("dateFrom={0}&dateTo={1}&timeZone={2}&action={3}",
"2018-12-24", "2018-12-24", 18, "filter"); //<-- Change this
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URI);
request.Method = "POST";
request.UserAgent = "";
request.Headers.Add("X-Requested-With", "XMLHttpRequest");
request.ContentType = "application/x-www-form-urlencoded"; //<-- Add this
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(requestBody);
}
WebResponse response = request.GetResponse();
string jsonData = String.Empty;
using (var reader = new StreamReader(response.GetResponseStream()))
{
jsonData = reader.ReadToEnd();
}
response.Close();

In PostMan, if you click the "Code" in the top right, under the send button, you can choose C# (RestSharp).. If you're not using RestSharp, there's a small amount of work to do to convert it to something else, but the basics are all there.
Here's the autogen output for your case (RestSharp):
var client = new RestClient("https://sslecal2.forexprostools.com/ajax.php");
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "bfd1a3b3-983f-4160-a091-6f0962413e58");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("X-Requested-With", "XMLHttpRequest");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("undefined", "dateFrom=2018-01-24&dateTo=2018-01-24&timeZone=18&action=filter", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Converting it to HttpWebRequest requires:
AddHeader -> Headers.Add
Specify method
Body data is set differently - take PostMan's string and write it to the request stream
Or install RestSharp free from NuGet

Related

SOLVED C# HttpWebResponse delivers different response than Postman

I'm consuming a Web API of an internal system in the company.
It's getting a payload in JSON format and returning a response with data in JSON format.
When sending the request with Postman, it returns the expected response (StatusCode=200 + a response text in JSON format). That means that everything is OK with the web service.
Now I have to develop an application in C# to send this HTTP request.
The problem is, that I receive as response content "OK" and not the expected JSON response gotten with Postman.
public HttpWebResponse SendRequest(string url, string checkOutFolder, string drawingNo, string login, string password)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/json";
request.Method = "GET";
request.Accept = "application/json";
string payload = GeneratePayLoad(checkOutFolder, drawingNo);
string header = CreateAuthorization(login, password);
request.Headers[HttpRequestHeader.Authorization] = header;
request.ServicePoint.Expect100Continue = false;
var type = request.GetType();
var currentMethod = type.GetProperty("CurrentMethod", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(request);
var methodType = currentMethod.GetType();
methodType.GetField("ContentBodyNotAllowed", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(currentMethod, false);
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(payload);
}
// Response
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
string responseContent = rd.ReadToEnd();
Console.WriteLine(responseContent);
}
return response;
}
Has anyone already experiences something similar.
Can you help me?
EDIT
Following your suggestions
1) Changed the method to POST -> result is still the same
2) Used Postman's code generator and RestSharp -> result is still the same
public void Request(string url, string checkOutFolder, string drawingNo, string login, string password)
{
var client = new RestClient(url);
var request = new RestRequest();
request.Method = Method.Post;
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Basic **********");
var body = GeneratePayLoad(checkOutFolder, drawingNo);
request.AddParameter("application/json", body, ParameterType.RequestBody);
var response = client.Execute(request);
Console.WriteLine(response.Content);
}
Changed to HttpClient -> result still the same
using (var client = new HttpClient())
{
string uri = "******************";
string path = "destinationpath";
var endpoint = new Uri(uri);
string payload = GeneratePayLoad(path, "100-0000947591");
//FormUrlEncodedContent form = new FormUrlEncodedContent(payload);
var stringContent = new StringContent(payload);
var payload2 = new StringContent(payload, Encoding.UTF8, "application/json");
var byteArray = Encoding.ASCII.GetBytes("*******");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var base64EncodedAuthenticationString = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(client.DefaultRequestHeaders.Authorization.ToString()));
var result = client.PostAsync(endpoint, stringContent).Result.Content.ReadAsStringAsync().Result;
Console.WriteLine("test");
}
Wrote a Python code using requests Package -> delivers the same as Postman. So the problem is in the C# code.
Does anyone have an idea what is going on?
SOLVED
The issue was on the payload generation!
The request needs to be an HTTP POST and not HTTP GET because it contains JSON payload.
request.Method = "GET"; should be request.Method = "POST";
That would be one of the issue(s). I am not sure if there is something else that is wrong, but try changing the request method to POST and try again.

C# Call Graph API with .Net Framework 4.0

Hey im trying to post an http request (Create Teams online meeting) to the Graph API under c# .Net Framework 4.0 so i cannot use the Graph-SDK and i cannot use the System.net.http libary (no httpClient). I tried HttpWebRequest but im having difficulties with posting Json to the API.
My Request Function looks like this:
private string SendHttpRequest(string Method, string ContentType, WebHeaderCollection Headers, string Content, string URI)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URI);
request.Method = Method;
request.Headers = Headers;
request.PreAuthenticate = true;
request.ContentType = ContentType;
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream());
requestWriter.Write(Content);
requestWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
var responseStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);
string responseText = responseReader.ReadToEnd();
responseReader.Close();
return responseText;
}
catch (Exception ex)
{
throw (ex);
}
}
And this works fine when my Content Type is text/xml(for a diffrent API) but not if its Application/Json.
I always get an Error 400 when i call HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Method = "POST"
ContentType = "application/json"
Headers = Headers.Set(HttpRequestHeader.Authorization, "Bearer " + accessToken);
Content = string jsonContent = JsonConvert.SerializeObject(Content);
URI = "https://graph.microsoft.com/v1.0/me/onlineMeetings"
for anyone with the same difficulties.
I was missing the Timezones in my startDateTime and endDateTime.
To add those i had to Format my DateTime i recive from my database.
This worked for me:
TimeAndOffset = new DateTimeOffset(reservation.beginnUhrzeit,
TimeZoneInfo.Local.GetUtcOffset(reservation.beginnUhrzeit));
teamsCreate.startDateTime = TimeAndOffset.ToString("o");
reservation.beginnUhrzeit is my Database variable
teamsCreate is an Object i can later serialize to Json
After that everything worked.

Why am I getting this 401 unauthorized error while using Hammock with the Tumblr API to retrieve likes?

Here is the code that I am using:
public static void FetchXML()
{
_url = new Uri("http://api.tumblr.com/v2/blog/" + _username + ".tumblr.com/likes?api_key=REc3Z6l4ZYss11a8lX6KKje0X8Hsi9U77SyaPbQrOBBCGJGA6D");
var client = new RestClient();
client.Authority = _url.ToString();
var request = new RestRequest();
request.AddParameter("limit", "20");
request.AddParameter("offset", _offset.ToString());
var response = client.Request(request);
var content = response.Content.ToString();
var parsedResponse = JsonParser.FromJson(content);
}
If I take the Uri value and paste it into my browser (using a valid Tumblr username) I'm getting the correct Json, but in my application the content of response is:
"{\"meta\":{\"status\":401,\"msg\":\"Unauthorized\"},\"response\":[]}"
Anyone have any idea why this is? According to the Tumblr API
retrieving likes should only need the API key, which I am providing.
Hi you can use the below code to get the response.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "GET";
request.ContentType = "Application/json";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receive = response.GetResponseStream();
StreamReader reader = new StreamReader(receive, Encoding.UTF8);
string respond = reader.ReadToEnd();

HttpWebRequest method GET/POST not working?

I am working with GoogleApi. I want to get accesstoken as response using Google api. when I am sending httpwebrequest for getting access token then
When I used :- request.Method = "POST"
Exception:- HTTP method POST is not supported by this URL
When I used :- request.Method = "GET"
Exception:- System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type
The actual request might look like:
POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded
code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=8819981768.apps.googleusercontent.com&
client_secret={client_secret}&
redirect_uri=https://oauth2-login-demo.appspot.com/code&
grant_type=authorization_code
A successful response is returned as a JSON array, similar to the following:
{
"access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
"expires_in":3920,
"token_type":"Bearer"
}
My Code is :-
var request = (HttpWebRequest)WebRequest.Create(#"https://accounts.google.com");
request.Method = "POST";
request.ContentType = "application/json";
//request.KeepAlive = false;
// request.Headers[HttpRequestHeader.Authorization] = "";
//request.ContentLength = 0;
using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = "{\"code\":\"4/M1IIC8htCuvYORuVJK16oadDb3Gd.cigIKgaPjvUYXE-sT2ZLcbSrckCLgwI\"," + "\"client_id\":\"841994137170.apps.googleusercontent.com\"," + "\"client_secret\":\"MXjKvevD_cKp5eQWZ1RFXfdo\"," + "\"redirect_uri\":\"http://gmailcheck.com/response.aspx\"," + "\"grant_type\":\"authorization_code\"}";
streamWriter.Write(json);
// streamWriter.Flush();
//streamWriter.Close();
}
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
StreamReader responsereader = new StreamReader(response.GetResponseStream());
var responsedata = responsereader.ReadToEnd();
//Session["responseinfo"] = responsereader;
}
}
catch (WebException ex)
{
using (WebResponse response = ex.Response)
{
var httpResponse = (HttpWebResponse)response;
using (Stream data = response.GetResponseStream())
{
var sr = new StreamReader(data);
throw new Exception(sr.ReadToEnd());
}
}
}
This is the problem:
var request = (HttpWebRequest)WebRequest.Create(#"https://accounts.google.com");
That's not the URL you showed originally. That's just the domain root. You need:
var request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
I've removed the # as your string doesn't include any line breaks or backslashes, so there's no benefit in using a verbatim string literal.
(Additionally, I'd expect this to be covered in the Google Client APIs - is it not?)

How to create folder and upload file using Rest api and oauth2.0

I want to create a folder and upload files using rest api
my code is like this
public string CreateFolder(string FolderName)
{
int WorkSpaceId = 330201;
int id = 168079105;
var queryString = HttpContext.Current.Session["tokenSession"];
var request = WebRequest.Create(RequestProfileUrl + FolderName);
request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.None;
request.Headers.Add("Authorization", "Bearer " + AccessToken);
request.ContentType = "multipart/form-data";
request.Method = "POST";
var response = request.GetResponse();
HttpContext.Current.Response.Redirect("" + request.RequestUri);
using (var responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
var responseText = reader.ReadToEnd();
reader.Close();
return responseText;
}
}
I have to do like this
POST https://apis.live.net/v5.0/me/skydrive
Authorization: Bearer ACCESS_TOKEN
Content-Type: multipart/form-data
{
"name": "My example folder"
}`
I added request header and content-type, I don't know how to add name parameter to my request.
To write the body of your POST request you need to get the request stream first, and then write to it. See the sample code below. Note that I changed the Content-Type from "multipart/form-data" to "application/json" as this is what your data seems to be.
// String with the body content
string postBody = "{\"name\":\"myfoldername\"}";
ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] byte1 = encoding.GetBytes (postBody);
// Set Content type to application/json
myHttpWebRequest.ContentType = "application/json";
// Set content length of the string being posted.
myHttpWebRequest.ContentLength = byte1.Length;
// Get the request stream and write body bytes to it
Stream newStream = myHttpWebRequest.GetRequestStream ();
newStream.Write (byte1, 0, byte1.Length);

Categories