Can someone help me with following API connection with C#. Never done any API connections before so i am a little unsure how it work. This is for a universal windows application so it will be using c# and XMAL.
Is it possible to do the following PHP API call below using C#:
<?php
$uri = 'http://api.football-data.org/v1/soccerseasons/354/fixtures/?matchday=22';
$reqPrefs['http']['method'] = 'GET';
$reqPrefs['http']['header'] = 'X-Auth-Token: YOUR_TOKEN';
$stream_context = stream_context_create($reqPrefs);
$response = file_get_contents($uri, false, $stream_context);
$fixtures = json_decode($response);
?>
Basically all i need to know is if it is even possible.
Thanks in advance.
It can be something like this (result is as text but you can json too):
HttpWebRequest request =(HttpWebRequest)WebRequest.Create("http://api.football-data.org/v1/soccerseasons/354/fixtures/?matchday=22");
request.Headers.Add("AUTHORIZATION", "Basic YTph");
request.ContentType = "text/html";
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream());
string ResultAsText = stream.ReadToEnd().ToString();
Here is my favorite example of calling a WEB API: http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client
It shows how to use HttpClient, uses async / await and introduces Formatters.
Related
This is the code which I have written on the app side, which is being developed using Xamarin
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(ApiUrl);
objRequest.Method = "POST";
objRequest.ContentType = "application/x-www-form-urlencoded";//"application/json;charset=utf-8";
objRequest.Headers.Add("Authentication", "web60134");
UTF8Encoding utf8Encoding = new UTF8Encoding();
byte[] arrRequest;
arrRequest = utf8Encoding.GetBytes(JsonReq);
objRequest.ContentLength = arrRequest.Length;
Stream requestStream = objRequest.GetRequestStream();
requestStream.Write(arrRequest, 0, arrRequest.Length);
requestStream.Close();
HttpWebResponse res = (HttpWebResponse)objRequest.GetResponse();
StreamReader streamReader = new StreamReader(res.GetResponseStream());
string result = streamReader.ReadToEnd();
This is the code written on the server side which is PHP
$recvd = $_POST['TH_ET_LoginProcess'];
$recvdArr = json_decode($recvd);
I tried using file_get_contents("php://input") but both the methods are returning null or nothing.
What is the best way to read JSON at web server using PHP in such scenario?
Best is a quite subjective term.
However what I am successfully using RestSharp in an Xamarin Android solution.
I also highly recommend PostMan and Fiddler for troubleshooting your service.
Regarding your code:
You should be disposing those objects that are disposable, preferable with the 'using' statement. This includes HttpWebResponse object is as well as the Stream ones.
WebRequest req = WebRequest.Create("[URL here]");
WebResponse rep = req.GetResponse();
I wanted some insights into the relevance of the GetResponse method, it appears to deprecated now.
This other method I hacked together gets the job done.
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(String.Format("http://mywebservicehere/dostuff?url=https://www.website.com"));
request.Method = "GET";
using (var response = (HttpWebResponse) (await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{
var encoding = ASCIIEncoding.ASCII;
StreamReader reader = new StreamReader(response.GetResponseStream(), encoding);
}
Wanted to know of any alternative methods others may have used? Thanks for the help!
I wanted some insights into the relevance of the GetResponse method,
it appears to deprecated now.
It is not deprecated, in the .NET for UWP, is is an async method.
WebRequest req = WebRequest.Create("[URL here]");
WebResponse rep = await req.GetResponseAsync();
Wanted to know of any alternative methods others may have used?
Besides the WebRequest class, there are another 2 HttpClient classes in the Windows Runtime Platform you can use to get a http response.
var client1 = new System.Net.Http.HttpClient();
var client2 = new Windows.Web.Http.HttpClient();
The System.Net.Http.HttpClient is in the .NET for UWP.
The Windows.Web.Http.HttpClient is in the Windows Runtime.
I cannot successfully call an API using C# at the moment. I have attached a screen shot of the call being successfully made with Chrome PostMan although I'm not able to replicate it in C#. He is my attempt so far which fails. The response I get back from the server is included below. Can anyone see what I'm doing wrong?
Many thanks,
James
Code Snippet
const string xml = "<Envelope><Body> <AddRecipient>...";
var req = (HttpWebRequest)WebRequest.Create(ApiUrl);
var requestBytes = System.Text.Encoding.ASCII.GetBytes(xml);
req.Method = "POST";
req.Headers.Add("Authorization", "Bearer " + token);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = requestBytes.Length;
var requestStream = req.GetRequestStream();
requestStream.Write(requestBytes, 0, requestBytes.Length);
requestStream.Close();
var res = (HttpWebResponse)req.GetResponse(); // Call API
var sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default);
var backstr = sr.ReadToEnd();
sr.Close();
res.Close();
Chrome PostMan
Response back from API
<Envelope><Body><RESULT><SUCCESS>false</SUCCESS></RESULT><Fault><Request/><FaultCode/><FaultString>Server Error</FaultString><detail><error><errorid>50</errorid><module/><class>SP.API</class><method/></error></detail></Fault></Body></Envelope>
Is there any documentation about what error 50 is? Could just be a bad pram? If not I recommend downloading fiddler. You can then properly compare the request from both PostMan and your application to see what the actual difference is.
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
I'm trying to write a function that can call a webmethod from a webserive given the method's name and URL of the webservice. I've found some code on a blog that does this just fine except for one detail. It requires that the request XML be provided as well. The goal here is to get the request XML template from the webservice itself. I'm sure this is possible somehow because I can see both the request and response XML templates if I access a webservice's URL in my browser.
This is the code which calls the webmethod programmatically:
XmlDocument doc = new XmlDocument();
//this is the problem. I need to get this automatically
doc.Load("../../request.xml");
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/dummyws/dummyws.asmx?op=HelloWorld");
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
Stream stm = req.GetRequestStream();
doc.Save(stm);
stm.Close();
WebResponse resp = req.GetResponse();
stm = resp.GetResponseStream();
StreamReader r = new StreamReader(stm);
Console.WriteLine(r.ReadToEnd());
Following on from the comments above. If you have a WSDL file that describes your service you use this as the information required to communicate with your web service.
Using a proxy class to communicate with your service proxy is an easy way to abstract yourself from the underlying plumbing of HTTP and XML.
There are ways of doing this at run-time - essentially generating the code that Visual Studio generates when you add a web service reference to your project.
I've used a solution that was based on: this newsgroup question, but there are also other examples out there.
FYI, your code is missing using blocks. It should be more like this:
XmlDocument doc = new XmlDocument();
//this is the problem. I need to get this automatically
doc.Load("../../request.xml");
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/dummyws/dummyws.asmx?op=HelloWorld");
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
using (Stream reqstm = req.GetRequestStream())
{
doc.Save(reqstm);
}
using (WebResponse resp = req.GetResponse())
{
using (Stream respstm = resp.GetResponseStream())
{
using (StreamReader r = new StreamReader(respstm))
{
Console.WriteLine(r.ReadToEnd());
}
}
}