I'm trying to do a HTTP GET request for a json file from an api in a C# application. I'm having trouble getting the authorization, request headers and the webresponse (.GetResponse not working).
The example on the api's site is in curl.
curl -H "Authorization: Bearer ACCESS_TOKEN" https://erikberg.com/nba/boxscore/20120621-oklahoma-city-thunder-at-miami-heat.json
Here is my request method, which will also include JSON deseralization
public static string HttpGet(string URI)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URI);
// Not sure if the credentials input is the correct
string cred = $"{"Bearer"} {"ACCESS_TOKEN_IS_A_GUID"}";
req.Headers[HttpRequestHeader.Authorization] = cred;
req.Method = "GET";
// GetResponse() is "red", won't work.
WebResponse response = req.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd().Trim();
}
}
EDIT It was resolved. The problem was that the request was for a GZIP file and that had to be decompressed
var request = (HttpWebRequest)WebRequest.Create(requestUri);
request.UserAgent = userAgent;
request.ContentType = "application/json";
request.Method = WebRequestMethods.Http.Get;
request.Headers[HttpRequestHeader.Authorization] = bearer;
request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip";
var response = (HttpWebResponse) request.GetResponse();
string jsonString;
using (var decompress = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
{
using (var sr = new StreamReader(decompress))
jsonString = sr.ReadToEnd().Trim();
}
_Game = JsonConvert.DeserializeObject<Game>(jsonString);
You are not getting it because you don't have access.
The cURL command from API's site(that you mentioned in your question) gives the following JSON
{
"error" : {
"code" : "401",
"description" : "Invalid access token: ACCESS_TOKEN"
}
}
And so does the following code:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("URL");
req.UserAgent = "Bearer";
WebResponse response = req.GetResponse();
So what you need is a valid username/password or userAgent. You might want to contact the site for that.
Related
I'm trying to exchange an authorisation code for an access token using C# on HRMRC Making Tax Digital API. I'm able to get the authorisation code alright which I thought would be the difficult bit.
I've also been able to use Postman to exchange the authorisation code my app has obtained for the access token. See the attached screen shots of Postman and below is my C# :
uri = "https://api.service.hmrc.gov.uk/oauth/token"
body = "client_id=MyClientId&client_secret=MyClientSecret&code=MyAuthorisationCode&grant_type=authorization_code&redirect_uri=http%253A%252F%252Flocalhost%253A80%252F"
private static AccessTokens GetTokens(string uri, string body)
{
AccessTokens tokens = null;
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.Accept = "application/vnd.hmrc.1.0+json";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = body.Length;
using (Stream requestStream = request.GetRequestStream())
{
StreamWriter writer = new StreamWriter(requestStream);
writer.Write(body);
writer.Close();
}
var response = (HttpWebResponse)request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
string json = reader.ReadToEnd();
reader.Close();
tokens = JsonConvert.DeserializeObj[1]ect(json, typeof(AccessTokens)) as AccessTokens;
}
return tokens;
}
I'm trying to use .net to put datapoints in OpenTSDB, using the HTTP /api/put API.
I've tried with httpclient, webRequest and HttpWebRequest. The outcome is always 400 - bad request: chunked request not supported.
I've tried my payload with an api tester (DHC) and works well.
I've tried to send a very small payload (even plain wrong, like "x") but the reply is always the same.
Here's one of my code instances:
public async static Task PutAsync(DataPoint dataPoint)
{
try
{
HttpWebRequest http = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:4242/api/put");
http.SendChunked = false;
http.Method = "POST";
http.ContentType = "application/json";
Encoding encoder = Encoding.UTF8;
byte[] data = encoder.GetBytes( dataPoint.ToJson() + Environment.NewLine);
http.Method = "POST";
http.ContentType = "application/json; charset=utf-8";
http.ContentLength = data.Length;
using (Stream stream = http.GetRequestStream())
{
stream.Write(data, 0, data.Length);
stream.Close();
}
WebResponse response = http.GetResponse();
var streamOutput = response.GetResponseStream();
StreamReader sr = new StreamReader(streamOutput);
string content = sr.ReadToEnd();
Console.WriteLine(content);
}
catch (WebException exc)
{
StreamReader reader = new StreamReader(exc.Response.GetResponseStream());
var content = reader.ReadToEnd();
}
return ;
}
where I explicitly set to false the SendChunked property.
note that other requests, like:
public static async Task<bool> Connect(Uri uri)
{
HttpWebRequest http = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:4242/api/version");
http.SendChunked = false;
http.Method = "GET";
// http.Headers.Clear();
//http.Headers.Add("Content-Type", "application/json");
http.ContentType = "application/json";
WebResponse response = http.GetResponse();
var stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
string content = sr.ReadToEnd();
Console.WriteLine(content);
return true;
}
work flawlessly.
I am sure I am doing something really wrong.
I'd like to to reimplement HTTP in Sockets from scratch.
I've found a solution I'd like to share here.
I've used wireshark to sniff my packets, and I've found that this header is added:
Expect: 100-continue\r\n
(see 8.2.3 of https://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html)
This is the culprit. I've read the post http://haacked.com/archive/2004/05/15/http-web-request-expect-100-continue.aspx/ by Phil Haack, and found that HttpWebRequest puts that header by default, unless you tell it to stop. In this article I've found that using ServicePointManager I can do just this.
Putting the following code on top of my method, when declaring the http object, makes it work very well, and solves my issue:
var uri = new Uri("http://127.0.0.1:4242/api/put");
var spm = ServicePointManager.FindServicePoint(uri);
spm.Expect100Continue = false;
HttpWebRequest http = (HttpWebRequest)WebRequest.Create(uri);
http.SendChunked = false;
I'm trying to make a request to the Square Connect api to list the payments. I'm receiving this error
"The remote server returned an error: (401) Unauthorized."
The api says
Open your favorite command-line application (such as Terminal if you're using a Mac) and run the following curl command, providing your access token where indicated:
curl -H "Authorization: Bearer PERSONAL_ACCESS_TOKEN" https://connect.squareup.com/v1/me/payments
Here is my code. What am I doing wrong?
WebRequest request = WebRequest.Create("https://connect.squareup.com/v1/me/payments");
request.ContentType = "application/json";
request.Method = "GET";
request.Headers("Authorization") = "XXXXX";
HttpWebResponse response = null;
string responseMessage = null;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK) {
using (Stream stream = response.GetResponseStream()) {
using (StreamReader reader = new StreamReader(stream)) {
responseMessage = reader.ReadToEnd();
}
}
}
Assert.IsNotNull(responseMessage);
var client = new RestSharp.RestClient();
var request = new RestRequest("https://connect.squareup.com/v1/me/payments", Method.GET);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Authorization", "Bearer xxxxx");
//setHeaders(request);
var Response = client.Execute(request);
Instead of
request.Headers("Authorization") = "XXXXX";
Do this
request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + yourPersonalAccessToken);
I want to login to this site: http://subcard.subway.co.uk/de_cardholder/JSP/login_reg.jsp
And i found out that I have to send a POST request to the server and I also know that I have to work with this POST request:
POST /de_cardholder/servlet/SPLoginServlet HTTP/1.1
Host: subcard.subway.co.uk
language=de&userID=ID&password=PASSWORD&transIdentType=1&programID=6
And after the login I want to parse the HTML data. But how can I implement the POST request on WP in C# and is it as easy as I think?
Try this,
Uri RequestUri = new Uri("subcard.subway.co.uk/de_cardholder/servlet/SPLoginServlet HTTP/1.1?language=de&userID=ID&password=PASSWORD&transIdentType=1&programID=6", UriKind.Absolute);
string PostData = "";
WebRequest webRequest;
webRequest = WebRequest.Create(RequestUri);
webRequest.Method = "POST";
webRequest.ContentType = "text/xml";
HttpWebResponse response;
string Response;
using (response = (HttpWebResponse)await webRequest.GetResponseAsync()) ;
using (Stream streamResponse = response.GetResponseStream())
using (StreamReader streamReader = new StreamReader(streamResponse))
{
Response = await streamReader.ReadToEndAsync();
}
if(Response != null)
{
//data should be available in Response
}
var postRequest = (HttpWebRequest)WebRequest.Create("your Url here");
postRequest.ContentType = "application/x-www-form-urlencoded";// you can give the type of request content here
postRequest.Method = "POST";
if you have any data to be posted along with the request as part of content and not as part of URL itself you can add this. example:- ( language=de&userID=ID&password=PASSWORD&transIdentType=1&programID=6)
using (var requestStream = await postRequest.GetRequestStreamAsync())
{
byte[] postDataArray = Encoding.UTF8.GetBytes("your request data");
await requestStream.WriteAsync(postDataArray, 0, postDataArray.Length);
}
if you do not have any data to be a send as content ignore the above code
WebResponse postResponse = await postRequest.GetResponseAsync();
if (postResponse != null)
{
var postResponseStream = postResponse.GetResponseStream();
var postStreamReader = new StreamReader(postResponseStream);
string response = await postStreamReader.ReadToEndAsync();// Result comes here
}
I'm attempting to retrieve an authentication token from Wordnik by using the provided API. However, I cannot seem to get it to work; I seem to be stuck getting 401 and 403 errors.
The following is the code I am using to request authentication from the API:
string authRequest =
String.Format("http://api.wordnik.com//v4/account.json/authenticate/{0}",
this.userName);
HttpWebRequest request = WebRequest.Create(authRequest) as HttpWebRequest;
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
// When this is added, I get 403 errors
///request.Headers.Add("api_key", APIKey);
string postData = "password=" + password;
byte[] encodedData = UTF8Encoding.UTF8.GetBytes(postData);
request.ContentLength = encodedData.Length;
Stream stream = request.GetRequestStream();
stream.Write(encodedData, 0, encodedData.Length);
stream.Close();
string responseText;
using(HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
using(StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseText = reader.ReadToEnd();
Console.WriteLine(responseText);
Console.ReadLine();
}
}
Can any of you tell me what I'm doing incorrectly?
Any input is appreciated.
You have a double slash in the request URL:
"http://api.wordnik.com//v4"