Consume RESt API from .NET

2019-03-08 17:04发布

I am trying to consume REST API from my .NET Application. This API's are all written in JAVA. I am asked to pass the authentication credentials vis HTTP headers. How can I pass these authentication credentials like 'DATE', 'AUTHORIZATION' and 'Accept' via HTTP headers.

Which class in .NET can I use to accomplish this task. Can anyone help me with this?

All your help will be appreciated.

Ajish.

4条回答
叛逆
2楼-- · 2019-03-08 17:12

Despite its somewhat misleading name, ADO.NET Data Services (which is part of .NET 3.5) contains APIs for both exposing and consuming REST-based services. In your case you can safely ignore the part that allows you to expose services and concentrate on the client part.

It supports LINQ and all sorts of goodness, allowing you to query your REST service like this:

var selectedOrders = from o in context.Orders
                     where o.Freight > 30
                     orderby o.ShippedDate descending 
                     select o;

There's more about it here. Give it a try - I've been pretty happy with it so far.

查看更多
Anthone
3楼-- · 2019-03-08 17:15

Update

This library has now been replaced by http://nuget.org/packages/Microsoft.Net.Http/2.1.10


Use the Microsoft.Http client library that is in WCF REST Starter Kit Preview 2.

Here is how you could use it:

    var client = new HttpClient();
    client.DefaultHeaders.Authorization = new Credential("ArbitraryAuthHeader");
    client.DefaultHeaders.Date = DateTime.Now;
    client.DefaultHeaders.Accept.Add("application/xml");

    var response = client.Get("http://example.org");

    var xmlString = response.Content.ReadAsString();
查看更多
仙女界的扛把子
4楼-- · 2019-03-08 17:18

Just to add a bit of value to this thread (I too was looking for a way to consume a RESTful service and easily provide credentials and came across this thread ... I did not have the "Date" requirement), Aaron Skonnard has written an excellent article on using the WCF REST Starter Kit called:

A Developer's Guide to the WCF REST Starter Kit

There is a very informative section on how to consume a RESTful service using HttpClient. And here's the code snippet to talk to Twitter:

HttpClient http = new HttpClient("http://twitter.com/statuses/");
http.TransportSettings.Credentials =
    new NetworkCredential("{username}", "{password}");
HttpResponseMessage resp = http.Get("friends_timeline.xml");
resp.EnsureStatusIsSuccessful();
ProcessStatuses(resp.Content.ReadAsStream());
查看更多
淡お忘
5楼-- · 2019-03-08 17:27

There are a number of ways taht you can do this but using the WebRequest objects is the fastest if you have just a few calls to complete.

This site, has a great overview of the process.

查看更多
登录 后发表回答