简体   繁体   中英

Calling Rest Api with HTTP authentication

I have to call a Rest API securely. I have an authenticate API which returns a token. I need to add this token the API I am calling.

This is the usual way I know of calling the Rest API . I need to append string token to this request.

        // *** Establish the request 
        string token= getAuthenticate(username,password,out token );
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(lcUrl);
        // *** Retrieve request info headers
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        StreamReader loResponseStream = new StreamReader(response.GetResponseStream());
        string lcHtml = loResponseStream.ReadToEnd();
        response.Close();
        loResponseStream.Close();

Not Sure what's the problem... To get the response from the Rest Uri you can do like below :

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(yourUrl + token); // Append Here
        request.Method = "GET"; // GET or POST Define Here
        //http.Accept = "application/json"; // Add if require
        //http.ContentType = "application/json"; // Add if require
        String test = String.Empty;
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            test = reader.ReadToEnd();
            reader.Close();
            dataStream.Close();
        }

Or You can use Simple requests through WebClient :

For Example:

WebClient webClient = new WebClient();
string json = string.Empty;
// Downloads JSon String
json = webClient.DownloadString("http://api.openweathermap.org/data/2.5/weather?q=London,uk"); // Replace your URL + Token...

There is third party component also available = RestSharp .

I am using HttpClient , no different at all. I thought this way more clean : http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

var uri = "http://example.com";
using (HttpClient httpClient = new HttpClient())
{
     httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token_you_want_to_used);

     var response = await httpClient.GetAsync(uri);
     string result = await response.Content.ReadAsStringAsync();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM