How to connect to Outpan.com API with C#? - c#

I am working on a university project in which I need to get some product information out of the database of outpan.com into a string or an array of strings.
I am new to coding, that's why I am needing quite a lot of help still. Does anyone of you know how to send a request & get the answer from a c#-environment (Windows Form Application)?
The description on outpan itself (https://www.outpan.com/developers.php) says to send the call by using HTTPS in curl, but what does it practically mean? Do I need to install extra libraries?
I would be glad, if someone could help me with this problem or provide me with a tutorial on how to make these curl calls to a database starting from a c# environment.
If there are more information needed about my settings, let me know.

The Outpan API uses Basic HTTP auth, so all the request will need to have a header like:
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
In the request. In order to do that with C#, you could do the following:
var request = (HttpWebRequest)WebRequest.Create("https://api.outpan.com/v1/products/0796435419035");
var encodedString = Convert.ToBase64String(Encoding.Default.GetBytes("-your-api-key-here-:"));
request.Headers["Authorization"] = "Basic " + encodedString;
var response = request.GetResponse();
For a full description of the header, check out the wiki page http://en.wikipedia.org/wiki/Basic_access_authentication. Note that the base64 encoded string can be in the form [username]:[password], but the outpan api docs ( https://www.outpan.com/developers.php ) write that they do not use the password part.
Also see: Forcing Basic Authentication in WebRequest for a nice method wrapper for this logic.

Related

What is an absolute bare bones httpclient configuration?

I'm coming to .net web api from a JavaScript background, and I'm trying to make a proxy to help with a cross domain JSON request. I'm GETing from a server I don't control the source code for, so I can't configure CORS directly. Likewise, it doesn't speak JSONP.
So two questions as I try to get my head around Web API:
1) Is Httpclient the right tool for this job? (if not, what is?)
2) If httpclient IS the right tool, what is an absolute bare bones httpclient config so I can test this out? Not worried about throwing exceptions or anything else other than just GETing API data and feeding it to a jQuery client.
I guess one other piece of information that would be nice would be building username / password authentication into the http request.
Any help is much appreciated, as are links to any good blogs / tutorials / etc that might help as an introduction to this sort of thing. I've watched several today alone, and I'm still not able to get a basic http request going on the server side without resorting to cutting / pasting other people's code.
Thanks in advance!
** EDIT - To make this question a bit more clear, what I'm trying to test is 1) Can the proxy connect to the third party server, which involves authentication via a username and password 2) Can the proxy then respond to the jQuery client request with the JSON data it received from the third party server.
Thanks to all who have taken the time to respond.
HttpClient seems to be ok in this job.
About the minimal config- it depends on what the third party expects. In most cases would work out-of-the-box, but there always may be some minor tweaks like headers and/or auth code.
I have just found some blog entry where some author shows how to test such a proxy and shows the proxy code too. Please see: http://www.davidbreyer.com/programming/2014/10/11/create-fake-responses-to-rest-service-calls-in-c/
You can find info about sending credentials here: How to use credentials in HttpClient in c#?
HTH
EDIT:
this sample code should work (copied from blog above and modified):
public class Proxy
{
public async Task<ExampleDto> GetExample(int id)
{
var client=new HttpClient();
//set some auth here
//set other headers
var response = client.GetAsync(
string.Format("/api/restserviceexample/{0}", id))
.Result.Content.ReadAsAsync<ExampleDto>();
return await response;
}
}
It's so simple that you can just run it and see if the other server responds. If not, you can play with headers - since all the session info and user auth info are sent using ookies and/or headers, all you have to do is to see how it's made with regular browser and then fake it on the server. Probably best tool for this job will be Fiddler.
However - there is one thing to consider. If the other service has special method for authorization (other than passing credentials with each request) the whole thing becomes tricky, since your proxy should perform authorization using their service, then store their auth cookie on the server or propagate them to the browser and attach them with all next requests.
First, you don't need ASP.NET with C# if you really want minimal.
.NET has great http handling without ASP. Check out classes like HttpListener, HttpListenerContext, HttpListenerRequest, etc... Yes, you'll have to write some boilerplate as your application, but these classes are pretty good.
See among others:
http://www.codeproject.com/script/Articles/ViewDownloads.aspx?aid=599978
Second, if you want user & password, I'd checkout using oauth authentication so you don't have to deal with them directly. Google Plus, Windows Live, Facebook, etc... all have similar OAuth 2.0 APIs for that. See among others:
http://msdn.microsoft.com/en-us/library/dn659750.aspx
https://developers.google.com/+/web/signin/server-side-flow
https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/v2.2

Web Search using C# Program

I am trying to do a web search from within a C# app. I am currently using this code that gets an error.
WebRequest http = HttpWebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)http.GetResponse(); //error occurs here
I keep getting "The remote name could not be resolved: 'search.yahooapis.com'".
Here is the code for the url parameter:
StringBuilder url = new StringBuilder();
url.Append("http://search.yahooapis.com/WebSearchService/V1/webSearch?");
url.Append("appid=YahooDemo&results=100&query=");
url.Append(HttpUtility.UrlEncode(searchFor));
The problem, I think, is that I need an API key from Yahoo in place of 'YahooDemo' in the above code. I went to http://developer.apps.yahoo.com/projects and got an application ID but when I enter it it still does not work? I think the problem is I did not know what to put in the Yahoo project for Application URL and Callback Domain - I don't really know what this even means? I am happy to use other providers such as Google or Bing if this makes it easier. But I am new to C# so really need detailed but simple explanations to understand what I need to do. I am a bit lost. In the end I basically just want to do a web search from my C# program to look for key words, so if their is an easier way to do this I am all for it. Any suggestions?

VLC authentication using HttpWebRequest

I'm trying to use VLC's HTTP interface to read the current playlist (GET /requests/playlist.xml).
This was working fine in an older version of VLC, but in recent versions they added a password option and then made it mandatory. (There is no username.)
I first tried using this:
request.Credentials = new NetworkCredential("", password);
request.PreAuthenticate = true;
However this resulted in a WebException reporting a 401 error. Snooping the traffic revealed that it sent one request that did not have the Authorization header, and then immediately reported the error without attempting to actually authenticate. (VLC did correctly respond with the WWW-Authenticate challenge.)
If I specify a non-blank username, then it sends the same request as before but then follows up with a second request that does specify the Authorization header -- which then fails because VLC rejects the username.
I finally managed to get it to work by setting the header explicitly:
var credential = Convert.ToBase64String(Encoding.Default.GetBytes(":" + password));
request.Headers[HttpRequestHeader.Authorization] = "Basic " + credential;
This seems like something that should have worked originally, though. Is this a bug in .NET (or WinInet), that it can't cope with blank usernames; or is it a bug in VLC, that it doesn't use a username; or is it a bug in my code, that I needed to set something else?
I've had the same issue, albeit I'm using an empty string for a password. There are tools such as ILSpy you can use to decompile .NET libraries you are using so you can view their source code. Although I haven't found anything, maybe you can use this to determine if it's a .NET issue. I've had this problem occur using both Basic and Digest authorization so I'd take a look at HttpWebRequest (which I assume you are using).
It seems setting the Authorization header manually is the way to go for now. Since you are using Basic, if you care about the security of your password, you might want to look into SSL if you aren't implementing it already.

Moodle and C# - Web Service Configuration

I'm currently stuck with quite a significant issue that i'm hoping someone may be able to shed some light on, regarding configuring an XML-RPC based web service to talk between my game based learning virtual world and a dedicated Moodle site
To the best of my knowledge, from following some sparse information on how to configure a Moodle web service, i've done the following steps:
Enabled Web Services
Enabled the XML-RPC protocol
Edited my admin role to allow use of the protocol and creation of a token for logging
in
Creation of a service for authenticated users which my admin has been added to
The moodle documentation sends you in a bit of a loop but from what I can see i've the check list covered
I'm now trying to plug this into the backend of my virtual world to populate my dynamic terrain engine with sets of topics,assignments etc based on what the user would have access to etc
My issue comes from the simple HttpWebRequest for retrieving the token for the user
I'm using the following method to return a string containing the token
public string GetToken(string uname,string pword)
{
byte[] buffer = Encoding.ASCII.GetBytes("username="+uname+"&password="+pword+"&service=reflex");
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url + "login/token.php?username=" + uname + "&password=" + pword + "&service=myservice");
WebReq.Method = WebRequestMethods.Http.Post;
WebReq.ContentType = "application/x-www-form-urlencoded";
WebReq.ContentLength = buffer.Length;
using(Stream PostData = WebReq.GetRequestStream())
PostData.Write(buffer, 0, buffer.Length);
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
using(StreamReader reader = new StreamReader(WebResp.GetResponseStream()))
return token = reader.ReadToEnd();
}
When I debug this to validate the token is generated, it throws an error saying the web service is down, but to the best of my knowledge the web service isnt called here, this uses a built in primitive php file to return a string and no more. I have checked the PostData.Write and its throwing a .Length NotSupportedException which i'm unsure as to if its having an impact upon the second using statement
I'm hoping if someone can aid regarding configuration settings that the next steps should fall into place easily as the XML-RPC dll seems quite robust and easy to use
Any help would be greatly appreciated
Many thanks
Barry
Now resolved
Worked around to retrieve the token manually through a sql call and have the web service functioning now
If you have a look in the table mdl_external_services there is a field called short name, which is likely null as you can't seem to populate it through the moodle UI. It's this value that needs to be used as the service parameter rather than the service name.

Is WebRequest The Right C# Tool For Interacting With Websites?

I'm writing a small tool in C# which will need to send and receive data to/from a website using POST and json formatting. I've never done anything like this before in C# (or any language really) so I'm struggling to find some useful information to get me started.
I've found some information on the WebRequest class in C# (specifically from here) but before I start diving into it, I wondered if this was the right tool for the job.
I've found plenty of tools to convert data into the json format but not much else, so any information would be really helpful here in case I end up down a dead end.
WebRequest and more specifically the HttpWebRequest class is a good starting point for what you want to achieve. To create the request you will use the WebRequest.Create and cast the created request to an HttpWebRequest to actually use it. You will then create your post data and send it to the stream like:
HttpWebRequest req = (HttpWebRequest)
WebRequest.Create("http://mysite.com/index.php");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
string postData = "var=value1&var2=value2";
req.ContentLength = postData.Length;
StreamWriter stOut = new
StreamWriter(req.GetRequestStream(),
System.Text.Encoding.ASCII);
stOut.Write(postData);
stOut.Close();
Similarly you can read the response back by using the GetResponse method which will allow you to read the resultant response stream and do whatever else you need to do. You can find more info on the class at:
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx
WebClient is sometimes easier to use than WebRequest. You may want to take a look at it.
For JSON deserialization you are going to want to look at the JavaScriptSerializer class.
WebClient example:
using (WebClient client = new WebClient ())
{
//manipulate request headers (optional)
client.Headers.Add (HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
//execute request and read response as string to console
using (StreamReader reader = new StreamReader(client.OpenRead(targetUri)))
{
string s = reader.ReadToEnd ();
Console.WriteLine (s);
}
}
Marked as wiki in case someone wants to update the code
When it comes to POSTing data to a web site, System.Net.HttpWebRequest (the HTTP-specific implementation of WebRequest) is a perfectly decent solution. It supports SSL, async requests and a bunch of other goodies, and is well-documented on MSDN.
The payload can be anything: data in JSON format or whatever -- as long as you set the ContentType property to something the server expects and understands (most likely application/json, text/json or text/x-json), all will be fine.
One potential issue when using HttpWebRequest from a system service: since it uses the IE proxy and credential information, default behavior may be a bit strange when running as the LOCALSYSTEM user (or basically any account that doesn't log on interactively on a regular basis). Setting the Proxy and Authentication properties to Nothing (or, as you C# folks prefer to call it, null, I guess) should avoid that.
I have used WebRequest for interacting with websites. It is the right 'tool'
I can't comment on the JSON aspect of your question.
The currently highest rated answer is helpful, but it doesn't send or receive JSON.
Here is an example that uses JSON for both sending and receiving:
How to post json object in web service
And here is the StackOverflow question that helped me most to solve this problem:
Problems sending and receiving JSON between ASP.net web service and ASP.Net web client
And here is another related question:
json call with C#
To convert from instance object to json formatted string and vice-versa, try out Json.NET:
http://json.codeplex.com/
I am currently using it for a project and it's easy to learn and work with and offers some flexibility in terms of serializing and custom type converters. It also supports a LINQ syntax for querying json input.
in 3.5 there is a built-in jsonserializer. The webrequest is the right class your looking for.
A few examples:
Link
http://dev.aol.com/blog/markdeveloper/ShareFileWithNETFramework
Link

Categories