I am trying to do the following using .NET
What would the C# code look like using HttpClient, if my username is test and password is password?
HTTP Method: GET
URL: http://webapi.ebayclassifieds.com/webapi/categories
Sample command:
curl --digest -u{username}:{password} http://webapi.ebayclassifieds.com/webapi/categories
Here is what I have but I don't get the html:
var client = new HttpClient();
var requestContent = new FormUrlEncodedContent(new[] {
new KeyValuePair<string, string>("-u", "{test}:{password}") });
HttpResponseMessage response = await client.PostAsync(
"http://webapi.ebayclassifieds.com/webapi/categories", requestContent);
// Get the response content.
HttpContent responseContent = response.Content;
var blah = response.Content.ReadAsStringAsync();
Try this one:
CredentialCache credCache = new CredentialCache();
credCache.Add (new Uri ("http://webapi.ebayclassifieds.com"), "Digest", new NetworkCredential ("username", "passwd"));
After that construct the HttpClient with the credential cache:
var httpClient = new HttpClient( new HttpClientHandler { Credentials = credCache});
Rest of the process is same. If you perform http POST then use PostAsync, and for http GET use GetAsync.
You'll find more detail about CredentialCache from here.
Related
I came with an issue this morning where the Api which I am calling is a Get Method but to get Get the Data from it I had to send the json body this is working good when I am testing it in the post man but I am not able to implement it in my project where I am calling this using HttpClient
here is the screenshot of post
It also have a bearer token which I pass in Authorization
Now when I am try to implement this at client side here is my code
var stringPayload = JsonConvert.SerializeObject(json);
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("https://myapiendpoint/serviceability/"),
Content = new StringContent(stringPayload, Encoding.UTF8, "application/json"),
};
var response = await client.SendAsync(request).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
when I call this method using this code I get
System.Net.HttpStatusCode.MethodNotAllowed - Status code 405
I also tried changing this line
Method = HttpMethod.Get to Method = HttpMethod.Post
but still getting same error
I know this is bad implementation at API Side the request ideally should be POST but changing this is not in my hand and hence need to find the solution
almost search all over and trying all the variant of using GET Method finally the solution which worked for me in this case was this
var client = new HttpClient();
client.BaseAddress = new Uri("https://baseApi/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", string.Format("Bearer {0}", token));
var query = new Dictionary<string, string>
{
["pickup_postcode"] = 400703,
["delivery_postcode"] = 421204,
["cod"] = "0",
["weight"] = 2,
};
var url = "methodurl";
var response = await client.GetAsync(QueryHelpers.AddQueryString(url, query));
var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return JsonConvert.DeserializeObject<MyModel>(responseBody);
Got QueryHelpers from Microsoft.AspNetCore.WebUtilities package
I'm integrating a service that returns a key when I a GET request to a URL that is in the following format:
https://username:password#service.com/refresh.key
When I access the URL in my browser, it returns the new key as expected, by when I do a GET request using HttpClient I get a 401.
HttpClient _client = new HttpClient();
var response = await _client.GetAsync(#"https://username:password#service.com/refresh.key"); // Returns a 401
I think it has something to do with the '#' in the URL, but I'm not sure how to fix it, I tried replacing it with '%40', but when I do that I get a UriFormatException.
Does anyone know how to do this?
You should modify Authorization header of HttpClient, can you try the code below;
HttpClient _client = new HttpClient();
byte[] usernamePasswordBytes = Encoding.ASCII.GetBytes("user:pass");
_client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(usernamePasswordBytes));
var response = await _client.GetAsync(#"https://service.com/refresh.key");
PS: Such username:pass#domain.com requests are BasicAuthentication request so in fact you try to make basic authentication request.
Hope this works for you
You don't need to provide credentials in url. Instead you can do:
using (var handler = new HttpClientHandler {Credentials = new NetworkCredential("username", "password")}) {
using (HttpClient _client = new HttpClient(handler)) {
var response = await _client.GetAsync(#"https://service.com/refresh.key");
}
}
I have OneDrive & Google Drive successfully processing chunked download however Dropbox is giving me grief because I cannot get the correct http request path to the file.
I am not an expert in rest url's & endpoints, maybe someone can point me in the right direction for the acceptable dropbox request format for the latest UWP SDK.
using (var httpRequest = new HttpRequestMessage())
{
string url = "https://content.dropboxapi.com/1/files/auto" + uri;
string accessKey = ApplicationData.Current.LocalSettings.Values[CommonData.dropboxAccessToken_Key].ToString();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
httpRequest.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", accessKey);
}
I have read docs on Dropbox and it is not clear on the formatting for me, also I could not find a clear example anywhere.
Thanks again!
According to your code, the problem here is in your authorization header. For Dropbox API, the correct authorization header should like following:
Authorization: Bearer <access token>
So we should change httpRequest.Headers.Authorization to
httpRequest.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
Then your code should be albe to work. Using "file.mp3" under "temp" folder for example.
The code may like:
var uri = "/temp/file.mp3";
using (var httpClient = new HttpClient())
{
using (var httpRequest = new HttpRequestMessage())
{
string url = "https://content.dropboxapi.com/1/files/auto" + Uri.EscapeDataString(uri);
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
httpRequest.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
var response = await httpClient.SendAsync(httpRequest);
if (response.IsSuccessStatusCode)
{
//TODO
}
}
}
I am using oAuth to authenticate my app. I managed to get a code, access_token and refresh_token. So the next step would be trying to get info about the current user.
public async void GetCurrentUser()
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", AccessToken);
var response = await client.GetAsync("https://oauth.reddit.com/api/v1/me");
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);
}
}
}
This is the method I am using to do that. However the response is always an 403 (Forbidden) error code. Any idea what could be wrong? The access_token is what I got when I made a request to https://oauth.reddit.com/api/v1/access_token
I think the token is correct because when I create the same request with Fiddler it works.
ANSWER:
Fixed it by adding a custom user-agent
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, _endpointUri + "me");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
request.Headers.Add("User-Agent", Uri.EscapeDataString("android:com.arnvanhoutte.redder:v1.2.3 (by /u/nerdiator)"));
var response = await client.SendAsync(request);
I am working with the Basecamp API which is a REST (JSON) API using basic HTTP authentication over HTTPS.
This should be a GET request but when I run my code using GET I am receiving:
Cannot send a content-body with this verb-type
When I run it as a POST, I receive:
{"status":"400","error":"Bad Request"}
Does anyone know why this may be occurring?
using (var httpClient = new HttpClient()) {
string userName = "someone#someone.com";
string password = "somepassword";
var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", userName, password)));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, "https://correctUrlHere);
requestMessage.Headers.Add("User-Agent", "TheProject (someone#someone.com)");
requestMessage.Content = new StringContent(string.Empty, Encoding.UTF8, "application/json");
var response = await httpClient.SendAsync(requestMessage);
var responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
In this code I obviously swapped out the username, password, project name, and URL but in the actual code they are all correct.
GET requests must pass their parameters as url query and not as request body.
http://example.com?p1=1&p2=helloworld
If you don't have any content, as your example suggests, omit setting it on the request.
The BadRequest result indicates some error with your payload (again: content seems to be empty).