I have little problem that I have been trying to solve for some time. I want to connect to a REST web service and I have the API key for that web service that I want to consume. I have tried the service in the Google REST console and it works fine.
But when I try to build a c# .net project for it I dont know how to set the api key for the authentication. I took this code from other site:
string url = "http://Demo.company.com/Data/Values/1029/CarPart/id/"
HttpWebRequest GETRequest = (HttpWebRequest)WebRequest.Create(url);
GETRequest.Method = "GET";
Console.WriteLine("Sending GET Request");
HttpWebResponse GETResponse = (HttpWebResponse)GETRequest.GetResponse();
Stream GETResponseStream = GETResponse.GetResponseStream();
StreamReader sr = new StreamReader(GETResponseStream);
Console.WriteLine("Response from Server");
Console.WriteLine(sr.ReadToEnd());
How can I authenticate this service with my Api key: asdf1234. I need to add it to my header but how? Can you show me some code example?
Cheers
Thor
You should be able to do something like:
HttpWebRequest GETRequest = (HttpWebRequest)WebRequest.Create(url);
GETRequest.Method = "GET";
GETRequest.Headers.Add("api-key", "asdf1234");
Where "api-key" is the name of the header you want to set.
Related
I have an external URL, like http://a.com/?id=5 (not in my project)
and I want my website to show this URL's contents,
ex.
My website(http://MyWebsite.com/?id=123) shows 3rd party's url (http://a.com/?id=5) contents
but I don't want the client side to get a real URL(http://a.com/?id=5), I'll check the AUTH first and then shows the page.
I assume that you do not have control over the server of "http://a.com/?id=5". I think there's no way to completely hide the external link to users. They can always look at the HTML source code and http requests & trace back the original location.
One possible solution to partially hide that external site is using curl equivalent of MVC, on your controller: after auth-ed, you request the website from "http://a.com/?id=5" and then return that to your user:
ASP.NET MVC - Using cURL or similar to perform requests in application:
I assume the request to "http://a.com/?id=5" is in GET method:
public string GetResponseText(string userAgent) {
string url = "http://a.com/?id=5";
string responseText = String.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.UserAgent = userAgent;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream())) {
responseText = sr.ReadToEnd();
}
return responseText;
}
then, you just need to call this in your controller. Pass the same userAgent from client so that they can view the website exactly like they open it with their web browsers:
return GetResponseText( request.UserAgent);
//request is the request passed to the controller for http://MyWebsite.com/?id=123
PS: I may not using the correct MVC API, but the idea is there. Just need to look up MVC document on HttpWebRequest to make it work correctly.
I just started using the Paypal API and I'm stuck on this problem.
I generate a paypal request in code and when I send it I get back the following.
TIMESTAMP=2011-05-16T01:26:37Z
CORRELATIONID=6d4327d15421f
ACK=Failure
L_ERRORCODE0=10001
L_SHORTMESSAGE0=Internal Error
L_LONGMESSAGE0=Timeout processing request
When I run through the debugger and copy the generated request url and paste it into my web browser, I get a success response....
I'm sending the request like this - c#
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
WebResponse response = req.GetResponse();
The same request, but one sent by code, and one copied to the browser produces to different results. Why is that?
I got same problem. When remove the
request.Method ="POST";
line, problem is solved.
I'm trying to send a simple POST request to a REST web service and print the response (code is below, mostly taken from Yahoo! developer documentation and the MSDN code snippets provided with some of the documentation). I would expect the client to send:
Request Method: POST (i.e. I expect $_SERVER['REQUEST_METHOD'] == 'POST' in PHP)
Data: foo=bar (i.e. $_POST['foo'] == 'bar' in PHP)
However, it seems to be sending:
Request Method: FOO=BARPOST
Data: (blank)
I know the API works as I've tested it with clients written in Python and PHP, so I'm pretty sure it must be a problem with my C#. I'm not a .NET programmer by trade so would appreciate any comments/pointers on how to figure out what the problem is - I'm sure it's something trivial but I can't spot it myself.
uri, user and password variables are set earlier in the code - they work fine with GET requests.
request = (HttpWebRequest) WebRequest.Create(uri);
request.Credentials = new NetworkCredential(user, password);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
string postData = "foo=bar";
request.ContentLength = postData.Length;
StreamWriter postStream = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
postStream.Write(postData);
postStream.Close();
response = (HttpWebResponse) request.GetResponse();
The REST API is written in PHP, and the $_POST array is empty on the server when using the C# client.
Eventually found the HttpWebRequest.PreAuthenticate property which seems to solve the problem if the code is edited like so:
request = (HttpWebRequest) WebRequest.Create(uri);
request.PreAuthenticate = true;
request.Credentials = new NetworkCredential(user, password);
request.Method = WebRequestMethods.Http.Post;
From the documentation I presume this forces authentication before the actual POST request is sent. I'm not sure why the class doesn't do this automatically (libraries for other languages make this process transparent, unless you explicitly turn it off), but it has solved the problem for me and may save someone else another 2 days of searching and hair-pulling.
For what it's worth, PreAuthenticate doesn't need to be set for GET requests, only POST, although if you do set it for a GET request everything will still work, but take slightly longer.
i need to visit a secure web service,
every request in the header need to carry a token.
i know the endpoint to the web service,
i also know how to create the token.
but i cannot see the WSDL for the webservice.
is there a way in C#, to create a soap client, without the WSDL file.
I have verified that this code, which uses the HttpWebRequest class, works:
// Takes an input of the SOAP service URL (url) and the XML to be sent to the
// service (xml).
public void PostXml(string url, string xml)
{
byte[] bytes = Encoding.UTF8.GetBytes(xml);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentLength = bytes.Length;
request.ContentType = "text/xml";
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
string message = String.Format("POST failed with HTTP {0}",
response.StatusCode);
throw new ApplicationException(message);
}
}
}
You will need to create the proper SOAP envelope and pass that in as the "xml" variable. It takes some reading. I found this SOAP Tutorial to be helpful.
A SOAP client is simply an HTTP client with more stuff in it. See the HttpWebRequest class. You'll then have to create your own SOAP message, perhaps using XML Serialization.
You could create your own service, expose it to have a WSDL and then generate the client from that... kind of the long way.
Can you ask the developers of the web service to send you the WSDL and XSD file(s) by email? If so, you can dump the files in a folder and then add a Service Reference using the WSDL on your hard disk.
What's the best way to consume secure REST web service in C#? Web Service username and password are supplied in URL...
Several options:
HttpWebRequest class. Powerful but sometimes complex to use.
WebClient class. Less features, but should work for simpler web services, and much simpler.
The new HttpClient in the WCF REST Starter Kit. (The Starter Kit is a separate download, not a part of the .NET Framework).
Use WebRequest class to make the request and HttpWebResponse to get the response.
I used following code for consuming webservice.My user name,password and Url are saved in variables UserName,Pwd and Url respectively.
WebRequest Webrequest;
HttpWebResponse response;
Webrequest = WebRequest.Create(Url);
byte[] auth1 = Encoding.UTF8.GetBytes(UserName + ":" + Pwd);
Webrequest.Headers["Authorization"] = "Basic " + System.Convert.ToBase64String(auth1);
Webrequest.Method = "GET";
Webrequest.ContentType = "application/atom+xml";
response = (HttpWebResponse)Webrequest.GetResponse();
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
string Response = streamReader.ReadToEnd();
Response string will be available in variable Response.
I hope the password in the URL is somwhow encrypted :). Maybe this will help you:
http://social.msdn.microsoft.com/forums/en-US/wcf/thread/3c8db0bf-984e-426b-b068-d80165ed1b37/
Based on the little information you provided I would say that using the HttpWebRequest class is your best option.
It is relatively easy to use, there are lots of examples of how to use it and it will work with any media-type the REST interface delivers. You have full access to Http status codes, and Http Headers.
What more can you ask for?