API call successfully from external client but not from c# - c#

I need to call client API-HTTPS (GET) with some specific headers
Accept:application/json,application/vnd.error+json
Date:2018-10-03T06:52:48Z
Authorization:<SECRETKEY>
In this scenario when I try to call it from client like Postman or Advanced REST client, API give proper result. But the same thing I tried with C# code which generates 401-Unauthorized errorcode.
For example If I'm using postman code for RestSharp (C#). It won't work from my code.
Postman screenshot:
Even I tried the same with HttpWebRequest and HttpClient too. But no luck.
Code which postman provided from code section is as below with some confidential information which I can't expose.
var client = new RestClient("https://**CLIENT_API_PATH**");
var request = new RestRequest(Method.GET);
request.AddHeader("Postman-Token", "ef8c2a79-a501-4cef-aa2e-bacdc9d3a922");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Authorization", "**SECRET_KEY**");
request.AddHeader("Date", "2018-10-03T06:52:48Z");
request.AddHeader("Accept", "application/json,application/vnd.error+json");
IRestResponse response = client.Execute(request);
In above code 3 parameters are compulsory and have to pass for successful call to API.
Date with the above mentioned format only.
Accept with above mentioned string only.
Authorization with specific authentication (custom by client).
As per suggested comment I also add fiddler data from the call.
Postman request fetch from fiddler
fiddler screenshot
C# api call code request from fiddler
fiddler screenshot
C# code debug result
visual studio debug screenshot

Try this.
public static string Get(Uri uri, string token)
{
string responseString = string.Empty;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "GET";
request.ContentType = "application/json;charset=utf-8";
request.Headers.Add("Authorization", string.Format("Bearer {0}", token));
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
StreamReader responseReader = new StreamReader(responseStream);
responseString = responseReader.ReadToEnd();
}
}
return responseString;
}

Related

C# winform send request content type application/x-www-form-urlencoded with Restsharp

I am developing an small app with C# window form.
I can use Restsharp to send any request with content type application/json. But with application/x-www-form-urlencoded the server always return nothing or Internal error.
I have tested this api with Postman and Restlet Client and it work well.
Following some example on internet but it not work too.
Here is my code:
var client = new RestClient("http://www.nhimanhma.com");
var request = new RestRequest("users/sign_in", Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
string formData = $"token={token}&user[email]={email}&user[password]={password}";
string urlEncode = RestSharp.Extensions.StringExtensions.UrlEncode(formData);
request.AddParameter("application/x-www-form-urlencoded", urlEncode, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var content = response.Content;

Get Request in C# Returning 401 Not Authorised

Currently trying to do a Get request as part of a c# program. The request works fine on Postman as it uses a header for authorization. However I cannot get the code working for the program to use this header correctly in its Get request. I've had a good look around and tried various bits of code I've found but haven't managed to resolve it so any help would be appreciated!
public string Connect()
{
using (WebClient wc = new WebClient())
{
string URI = "myURL.com";
wc.Headers.Add("Content-Type", "text");
wc.Headers[HttpRequestHeader.Authorization] = "Bearer OEMwNjI2ODQtMTc3OC00RkIxLTgyN0YtNzEzRkE5NzY3RTc3";//this is the entry code/key
string HtmlResult = wc.DownloadString(URI);
return HtmlResult;
}
}
Above is one method inside the class.
Below is another attempt which is an extension method that gets passed the URL:
public static string GetXml(this string destinationUrl)
{
HttpWebRequest request =
(HttpWebRequest)WebRequest.Create(destinationUrl);
request.Method = "GET";
request.Headers[HttpRequestHeader.Authorization] = "Bearer
OEMwNjI2ODQtMTc3OC00RkIxLTgyN0YtNzEzRkE5NzY3RTc3";
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
string responseStr = new
StreamReader(responseStream).ReadToEnd();
return responseStr;
}
else
{
Console.Write(String.Format("{0}({1})",
response.StatusDescription, response.StatusCode));
}
return null;
}
Might I recommend the very handy RestSharp package (find it on Nuget).
It turns your current code into something like
public string Connect()
{
var client = new RestClient();
var request = new RestRequest("myURL.com", Method.GET);
request.AddParameter("Authorization", "Bearer OEMwNjI2ODQtMTc3OC00RkIxLTgyN0YtNzEzRkE5NzY3RTc3");
var response = client.Execute(request);
return response.Content;
}
It's much more succinct and easier to use (in my opinion) and thus lessens the likelihood of passing in or using incorrect methods.
If you're still having issues getting data back/connecting. Then using PostMan click Code in the upper right of PostMan and select the C# (RestSharp) option. Whatever is generated there matches exactly what PostMan is sending. Copy that over and you should get data back that matches your PostMan request.

Why python request working but C# request not working?

First, i try to post the script in PostMan tool.
{"AO":"ECHO"}
It working fine. Then i'm writing this request in C# but it not working.
And more i wrote the request again in Python, and it working well.
But my project is in Microsoft C#. I dont want to run script Python in C# at all.
==== Python =========
import httplib
import json
import sys
data = '{"AO":"ECHO"}'
headers = {"Content-Type": "application/json", "Connection": "Keep-Alive" }
conn = httplib.HTTPConnection("http://10.10.10.1",1040)
conn.request("POST", "/guardian", data, headers)
response = conn.getresponse()
print response.status, response.reason
print response.msg
==== C# ============
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://10.10.10.1:1040/guardian");
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/json";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"AO\":\"ECHO\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
}
}
I try to put "ContentLength" but it still timeout exception.
And i try to using RestSharp, it's not timeout but return null.
Any one please help...
var client = new RestClient("http://10.10.10.1:1040/guardian");
var request = new RestRequest();
request.Method = Method.POST;
request.AddHeader("Content-Type", "application/json");
request.Parameters.Clear();
request.RequestFormat = DataFormat.Json;
request.AddBody(new { AO = "ECHO" });
var response = client.Execute(request);
var content = response.Content;
Please help me,
I dont understand why it working fine in python.
But why it not working in C#.
I try to find many request in C# but it got error exception with timeout.
Python will automatically add Content-Length http header.
https://docs.python.org/2/library/httplib.html#httpconnection-objects
I think you might have to set this header manually in C#.
httpWebRequest.ContentLength = json.length;
Depending on the server, you may have to set UserAgent as well.
httpWebRequest.UserAgent=".NET Framework Test Client";

using Rest client and getting statuscode 406 not acceptable

I'm using RestClient and redirecting the request to external REST webservice (java) as RestRequest. I'm getting HTTP statuscode 'not acceptable' and also the repsonse.content is something like this "The resource cannot be displayed because the file extension is not being accepted by your browser."
the operation is successful but not able to get the required response which is nothing but a string value.
below is code snippet:
var client = new RestClient();
client.BaseUrl = JavaWSURI;
var request = new RestRequest();
//request.AddHeader("Content-Length", int.MaxValue.ToString());
//request.AddHeader("Content-Type", "text/html; charset=utf-8");
// jsonD is JSON input object
request.AddParameter("application/json", jsonD, ParameterType.RequestBody);
request.Method = Method.POST;
request.RequestFormat = DataFormat.Json;
// The server's Rest method will probably return something
var response = client.Execute(request) as RestResponse;
From the error message, it sounds like you may need to add an 'Accept' header to the request
Add an Accept request header as follows:
request.AddHeader("Accept",
"text/html, application/xhtml+xml, application/xml;q=0.9, image/webp, */*;q=0.8");
Please note you may need to change the value depending on your content.

How do I post to GitHub API v3

I am using GitHub API v3 with C#. I am able to get the access token and using that I am able to get the user information and repo info.
But when I try to create a new repo I am getting the error as Unauthorized.
I am using HttpWebRequest to post data, which can be seen below. Please suggest me some C# sample or sample code.
(..)string[] paramName, string[] paramVal, string json, string accessToken)
{
HttpWebRequest req = WebRequest.Create(new Uri(url)) as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/json";
StreamWriter writer = new StreamWriter(req.GetRequestStream());
writer.Write(json);
writer.Close();
string result = null;
using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
{
StreamReader reader =
new StreamReader(resp.GetResponseStream());
result = reader.ReadToEnd();
}(..)
Note: I am not sure where i need to add the accesstoken. I have tried in headers as well as in the url, but none of them works.
Are you using the C# Github API example code? I would look at that code to see if it does what you need.
You can use basic auth pretty easily by just adding auth to the request headers:
request.Headers.Add("Authorization","Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(username +":"+password)));
Sorry havent used the access token stuff yet.
You need to add this token here:
req.UserAgent = "My App";
req.Headers.Add("Authorization", string.Format("Token {0}", "..token..");
Try
rec.Credentials = CredentialCache.DefaultCredentials;
or use non-default credentials.
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.credentials.aspx

Categories