How to use HttpWebRequest and URL for API calls? - c#

I wrote a dll using HttpClient and tested it. It was working fine and then suddenly stopped working and instead of sending application/json started to send text/plain. In any case, I was advised to use HttpWebRequest instead of HttpClient. So I am trying to change my working code to that form. I also asked that question here https://social.msdn.microsoft.com/Forums/vstudio/en-US/e396d8ff-5260-42cd-aa5a-0a220d8bf123/switching-from-httpclient-to-webclient?forum=csharpgeneral
My problem is the following. I have host URL https://someSite.com and I also have two URLs which implement the API I need in the form of url = "/integrationapi//Attraction/Tickets/Validate"
I am not sure how should I create my request variable. I have a separate method which I call before attempting to get a response, e.g.
private void SetRequestHeaders(string tcHost, string tcUserName, string tcPassword, int tnTimeout)
{
request = WebRequest.Create(tcHost) as HttpWebRequest;
request.Host = tcHost;
request.Headers.Remove("Accept");
request.Headers.Add("Accept", "application/json");
string authorizationKey = Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", tcUserName, tcPassword)));
request.Headers.Add("Authorization", "Basic " + authorizationKey);
request.Timeout = tnTimeout * 1000;
}
Now, how should I use that request variable to call the API Url I need?

Related

SoapHttpClientProtocol.Invoke is making a POST request and I want it to make GET, how do I do it?

This is part of the code in the class I use to call the web service (this class inherits from SoapHttpClientProtocol). Whenever I call localidades() I get error 405 from the server, this is because localidades() is sending a post instead of a get, and the server is configured to allow get only. How can I change request type?
I tried to change request type by overrideing the GetWebRequest() method (apart from adding basic authentication), but it is only adding the basic authentication and not changing the request type.
protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
var request = base.GetWebRequest(uri);
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes("username" + ":" + "password"));
request.Headers.Add("Authorization", "Basic " + encoded);
request.Method = System.Net.WebRequestMethods.Http.Get;
return request;
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/localidades", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public string localidades() {
object[] results = this.Invoke("localidades", new object[0]);
return ((string)(results[0]));
}
SOAP is always an HTTP POST. If the server expects a GET, it isn't hosting the SOAP service correctly.

How to make REST GET in Asp.net C#?

I can get an access token of Office 365. I can not make a REST request (GET) attaching this token in the header.
I'm using this code:
RestClient client = new RestClient();
client.EndPoint = #"https://outlook.office365.com/api/v1.0/me/folders/inbox/messages?$top=10";
client.Method = HttpVerb.GET;
client.ContentType = "application/json";
client.PostData = "authorization: Bearer " + myAccesToken.ToString();
String json = client.MakeRequest();
I've tested the access token in http://jwt.calebb.net and it's ok.
But it's always returning:
The remote server returned an error: (400) Bad Request.
I'm kind a knewby to REST and my english is not that good... Sorry! :)
(RE)EDIT
I've tried with RestSharp and I've simplified a bit my code...
Now I'm using my access token to make the GET request.
How do I add the "authorization bearer" to my request?
Is it like this?
//Ask for the token
var client = new RestClient("https://login.windows.net/common/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddParameter("grant_type", "authorization_code");
request.AddParameter("code", Request.QueryString["code"]);
request.AddParameter("redirect_uri", myRedirectUri);
request.AddParameter("client_id", myClientID);
request.AddParameter("client_secret", myClientSecret);
IRestResponse response = client.Execute(request);
string content = "[" + response.Content + "]";
DataTable dadosToken = (DataTable)JsonConvert.DeserializeObject<DataTable>(content);
//I don't need a DataTable, but it was a way to retrieve my access token... :)
//Ask for info with the access token
var client2 = new RestClient("https://outlook.office365.com/api/v1.0/me");
var request2 = new RestRequest(Method.GET);
request2.AddHeader("authorization", myToken.ToString());
//I've tried this way also:
//client2.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(dadosToken.Rows[0]["access_token"].ToString(), "Bearer");
IRestResponse response2 = client2.Execute(request2);
string content2 = "[" + response2.Content + "]";
Response.Write(content2); //this returns NOTHING!
Thanks again!
You can also use Fiddler to figure out if the Request is well formed.
Try a simpler endpoint first like: https://outlook.office365.com/api/v1.0/me
and check if the right data comes back. You can call this endpoint just from the browser and also look at the request/respond inside Fiddler.
The first thing to check: Is it a bad request. This usually means the method can't be found or the given parameters cannot be located. Check the deploy and make sure it is the most up to date version and also check that your server is actually running.

Using the TeamViewer API

I am looking to create a C# application that will report on the connections that we make to customers. I am looking into the TeamViewer API, but I cannot get the code below to authenticate:
string accessToken = "xxxxxxxxxxxxxxxxxxx";
string apiVersion = "v1";
string tvApiBaseUrl = "https://webapi.teamviewer.com";
string address = tvApiBaseUrl + "/api/" + apiVersion + "/reports/connections";
try
{
// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Headers.Add("Bearer", accessToken);
request.Method = "GET";
WebResponse webResp = request.GetResponse();
}
catch (Exception)
{
// Do nothing for now
}
Use fiddler and make sure your requests include the authorization header.
All API requests need to include the "Authorization" header if the API function requires an access token.
Example
GET /api/v1/users HTTP/1.1
Host: webapi.teamviewer.com
Authorization: Bearer 54213-2YotnFZFEjr1zCsicMWp
Also examine what they are sending you back, it may provide a clue.
UPDATE
Try this change
request.Headers.Add("Authorization", "Bearer " + accessToken);

LinkedIn - How to get access token?

I'm trying to get access token from LinkedIn.
I'm follwing this URL https://developer.linkedin.com/documents/authentication
I am able to get an authorization code.
But when I'm passing the authorization code to this URL
https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code &code=AUTHORIZATION_CODE &redirect_uri=YOUR_REDIRECT_URI &client_id=YOUR_API_KEY &client_secret=YOUR_SECRET_KEY
I get an error in the below format
{"error":"invalid_request","error_description":"missing required parameters, includes an invalid parameter value, parameter more then once. : Unable to retrieve access token : appId or redirect uri does not match authorization code or authorization code expired"}
Any ideas? Thanks in advance.
This is because authorization code expires in 20 seconds. So you have to get the Access Token within that time frame.
I got the same error as you. I also met the following conditions:
My request was a POST request.
My redirect_uri's were the same in /authorization and /accessToken calls.
The /accessToken call was executed immediately after receiving the authorization code, so
it wouldn't expire.
What finally did the trick for me was revoking the access token generated on the application details page on https://www.linkedin.com/secure/developer.
This is an access token for oAuth 1.a and is not compatible with oAuth 2.0 on which the linkedIn api is currently running.
After revoking this access token I was able to get a new one with the /authorization and /accessToken calls.
I see this is an older thread, however if it will help anyone, here is my working solution, working on MVC core 2.0 as of december 2018:
first, redirect to LinkedIn like this
var url = "https://" + Request.Host + "/Login/LoginLinkedIn";
url = WebUtility.UrlEncode(url);
var redirectLinkedIn = "https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=*ClientId*&client_secret=*ClientSecret*&redirect_uri=" + url + "&state=*random required nummeric value*";
return Redirect(redirectLinkedIn);
after that, you will receive the answer in your Login/LoginLinkedIn action (don't forget to specify this path in your app settings Authorized Redirect URLs).
There you will use this private method to get a dynamic object filled with user data
private dynamic GetLinkedInUser(string code)
{
dynamic jresult;
NameValueCollection parameters = new NameValueCollection {
{"client_id", *ClientId*},
{"client_secret", *ClientSecret*},
{"grant_type", "authorization_code"},
{"redirect_uri", "https://" + Request.Host + "/Login/LoginLinkedIn"},
{"code", code}
};
WebClient client = new WebClient();
byte[] result = client.UploadValues("https://www.linkedin.com/oauth/v2/accessToken", "POST", parameters);
string response = System.Text.Encoding.Default.GetString(result);
string accessToken = JsonConvert.DeserializeObject<dynamic>(response).access_token;
WebRequest webReq = WebRequest.Create("https://api.linkedin.com/v1/people/~:(id,email-address,first-name,last-name)?format=json");
webReq.Method = "GET";
webReq.Headers.Add("Authorization","Bearer "+accessToken);
HttpWebResponse webResponse = (HttpWebResponse)webReq.GetResponse();
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream())) {
string objText = reader.ReadToEnd();
jresult = JsonConvert.DeserializeObject<dynamic>(objText);
}
return jresult;
}
hope it helps someone :)

How do I connect to the Asana Rest API using c#?

Does anyone have a snippet of code for connecting to the Asana API using c#?
There is a Hello World application on their site but unfortunately it is written in ruby.
https://asana.com/developers/documentation/examples-tutorials/hello-world
I'm doing this as a quick side project and can only dedicate a small amount of time to it. Any help would be greatly appreciated.
Thanks in advance!
Follow up:
I've tried multiple ways of accessing/authentication and I keep getting a 401 Not Authorized error.
My latest code looks like this:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://app.asana.com/api/1.0/users/me");
request.Method = "GET";
request.Headers.Add("Authorization: Basic " + "*MyUniqueAPIKey*");
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "application/json";
WebResponse ws = request.GetResponse();
Try this code. I was able to get a list of users with it:
const string apiKey = "whateverYourApiKeyIs";
public string GetUsers()
{
var req = WebRequest.Create("https://app.asana.com/api/1.0/users");
SetBasicAuthentication(req);
return new StreamReader(req.GetResponse().GetResponseStream()).ReadToEnd();
}
void SetBasicAuthentication(WebRequest req)
{
var authInfo = apiKey + ":";
var encodedAuthInfo = Convert.ToBase64String(
Encoding.Default.GetBytes(authInfo));
req.Headers.Add("Authorization", "Basic " + encodedAuthInfo);
}
This just returns the data as a string. Parsing the JSON is left as an exercise for the reader. ;)
I borrowed the SetBasicAuthentication method from here:
Forcing basic http authentication for HttpWebRequest (in .NET/C#)
You could try using my library, AsanaNet :)
https://github.com/acron0/AsanaNet
You need to do HTTP requests, there are so many tutorials like this one
http://msdn.microsoft.com/en-us/library/debx8sh9(v=vs.80).aspx

Categories

Resources