Reputation: 479
I am trying to consume an API in C#, this is the code for the request. It should be a simple JSON API, however I'm getting some irregularities here.
public static HttpResponseMessage sendRequest(List<Header> headers, string endpoint, string api_key, string api_secret)
{
using (var client = new HttpClient())
{
List<Header> headerlist = new List<Header>{};
if(headers != null)
headerlist = headers;
List<Header> signed = Helpers.sign(endpoint, api_secret);
foreach (Header header in signed)
{
headerlist.Add(header);
}
client.BaseAddress = new Uri("https://api.coinkite.com");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("X-CK-Key", api_key);
foreach (Header header in headerlist)
{
client.DefaultRequestHeaders.Add(header.Name, header.Data);
}
HttpResponseMessage response = client.GetAsync(endpoint).Result;
return response;
}
}
Which I am calling via
HttpResponseMessage result = Requests.sendRequest(null, "/v1/my/self", api_key, api_secret);
return result.Content.ToString();
However, when I write that to console it looks like:
System.Net.Http.SteamContent
Any clue as to what the issue is? I am not too familiar with the stream content type.
Upvotes: 1
Views: 6037
Reputation: 456
If you are only interested in the contents, you can get the string directly by changing
HttpResponseMessage response = client.GetAsync(endpoint).Result;
to
string response = client.GetStringAsync(endpoint).Result;
https://msdn.microsoft.com/en-us/library/hh551746(v=vs.118).aspx
Upvotes: 0
Reputation: 2142
Call GetResponse() on the HttpResponseMessage
Stream stream = result.GetResponseStream();
StreamReader readStream = new StreamReader(stream, Encoding.UTF8);
return readStream.ReadToEnd();
Upvotes: 0
Reputation:
HttpContent does not implement ToString method. So you need to use result.Content.CopyToAsync(Stream)
to copy the result content to a Stream.
Then you can use StreamReader to read that Stream.
Or you can use
string resultString = result.Content.ReadAsStringAsync().Result;
to read the result as string directly.This method no need to use StreamReader so I suggest this way.
Upvotes: 5