I am having some issues with HttpClient POST on my windows phone app. Using the following code only returns the headers, but not the json response body that i need.
FormUrlEncodedContent formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("key", apiKey)
});
HttpClient client = new HttpClient();
var response = await client.PostAsync(loginUrl, formContent);
var response = await client.PostAsync(loginUrl, formContent);
will only return you a HttpResponseMessage, you will need to read the content from it like so to get the JSON/XML data.
string response_data = await response.Content.ReadAsStringAsync();
Now response_data will equal what you are looking for.
Related
I am trying to use System.Net.Http.HttpClient PostAsync method to make an api call. It hangs forever after await _httpClient.PostAsync(requestUri, stringContent);
HttpClient configuration :
_httpClient = new System.Net.Http.HttpClient(new HttpClientHandler
{
UseDefaultCredentials = WithDefaultCredentials,
AllowAutoRedirect = false
});
_httpClient.DefaultRequestHeaders.Accept.Clear();
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(APPLICATION_JSON));
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(ApplicationXWwwFormUrlencoded));
if (!string.IsNullOrEmpty(CultureInfo.CurrentUICulture.Name))
{
_httpClient.DefaultRequestHeaders.AcceptLanguage.Add(new
StringWithQualityHeaderValue(CultureInfo.CurrentUICulture.Name));
}
PostAsync call :
var stringContent = new StringContent(content);
stringContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
var response = await _httpClient.PostAsync(requestUri, stringContent);
var responseContent = await response.Content.ReadAsStringAsync();
Using FormUrlEncodedContent instead of string content fixed my problem :
var requestContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("username", username),
// ...
});
var response = await _httpClient.PostAsync(requestUri, requestContent);
var responseContent = await response.Content.ReadAsStringAsync();
Need to develop a C# application to create new RT tickets, but the example code for c# on https://rt-wiki.bestpractical.com/wiki/REST#C.23 is not working.
I have found information from different places but none of them really have example on how to create a new rt ticket by using C# HttpClient.
Here is my attempt:
private static async void HTTP_Create()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(baseURL);
string ticketUri = string.Format("REST/1.0/ticket/new?user={0}&pass={1}", testUser.UserName, testUser.Password);
// Doesn't work
var TicketDataContent = new List<KeyValuePair<string, string>>();
TicketDataContent.Add(new KeyValuePair<string, string>("id", "ticket/new"));
TicketDataContent.Add(new KeyValuePair<string, string>("Queue", "queue name"));
TicketDataContent.Add(new KeyValuePair<string, string>("Requestor", "name#email.com"));
TicketDataContent.Add(new KeyValuePair<string, string>("Owner", "owner#email.com)"));
TicketDataContent.Add(new KeyValuePair<string, string>("Subject", "Created by C#"));
TicketDataContent.Add(new KeyValuePair<string, string>("Text", "Ticket body with messages related to this ticket"));
var ticketContent = new MultipartFormDataContent();
ticketContent.Add(new FormUrlEncodedContent(TicketDataContent), "content");
var response = await client.PostAsync(baseURL + ticketUri, ticketContent);
Console.WriteLine("Response StatusCode: " + response.StatusCode.ToString());
var retContent = response.Content;
var retMsg = await response.Content.ReadAsStringAsync();
Console.WriteLine(retMsg);
}
I got the following response:
Response StatusCode: OK
RT/4.4.2 200 Ok
# Required: id, Queue
Any help is appreciated. Thanks!
I am trying to figure out what I can do (logging, things to check) before having to read server logs as I don't want to miss something stupid before requesting that.
Here is my code:
const string URL = "https://SomeURL/api/security/";
string urlParameters = string.Format("grant_type=password&username={0}&password={1}", username, password);
StringContent content = new StringContent(urlParameters, Encoding.UTF8, "application/x-www-form-urlencoded");
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
StringContent content = new StringContent(urlParameters, Encoding.UTF8, "application/x-www-form-urlencoded");
var tokenResponse = client.PostAsync("token", content).Result;
I am a little newer to this so I'm not sure what to check next but have tried the same request using postman and get a response with my token so it looks like I am missing something or maybe formatting something incorrectly?
I was following an online course, and the code for setting the URL parameters were set like this:
public async Task<AuthenticatedUser> Authenticate(string userName, string password)
{
var data = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username ", "userName"),
new KeyValuePair<string, string>("password", "password")
});
using (HttpResponseMessage response = await apiClient.PostAsync("/Token", data))
{
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsAsync<AuthenticatedUser>();
return result;
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
}
When testing, found that 500 error was being returned for the PostAsync call. I checked my URL address and parameters and they all looked correct. If I tested in Swagger, then I received a 200 status and token was shown.
Following the link by Thomas Levesque I changed how the data variables were set to :
var data = new FormUrlEncodedContent(new Dictionary<string, string>
{
["grant_type"] = "password",
["username"] = username,
["password"] = password
});
Now the response status is 200 and the AuthenticatedUser model is populated correctly. However I couldn't understand why Dictionary seem to work and KeyValuePair didn't. So I created the list and then encoded it:
var dataList = new[]
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password", password)
};
var content = new FormUrlEncodedContent(dataList);
using (HttpResponseMessage response = await apiClient.PostAsync(requestUrl, content))
This also worked. I freely admit that I do not fully understand why.....yet.
I did not URL encode my parameters, here's the fix (probably a better way of doing it).
string urlParameters = string.Format("grant_type=password&username={0}&password={1}", Uri.EscapeDataString(username), Uri.EscapeDataString(password));
I am trying to make a POST to the Vimeo API but I am getting 401 Authorization Required.
This is my code for the request (I am just sending the first request that the docs says should return me a ticket ID for uploading).
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://api.vimeo.com");
var byteArray = Encoding.ASCII.GetBytes(accessToken);
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var form = new FormUrlEncodedContent(new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("type","POST")
});
var response = await client.PostAsync("/me/videos", form);
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadAsStringAsync();
I also tried adding access token like this:
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic", accessToken);
It always return 401.
What is proper way to add the access token?
This is how header must be:
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", accessToken);
I have a Windows Phone application in C#. I am trying send a image (byte[]) and a session token (string) to my django server, but not how to do it.
I 've looked at other post but it does not work what they do , or classes that use do not exist.
The header of my function is:
public static async Task<bool> sendImagePerfil(string token, byte[] imagen)
{
using (var client = new HttpClient())
{
var values = new List<KeyValuePair<string, string>>();
values.Add(new KeyValuePair<string, string>("token", token));
values.Add(new KeyValuePair<string, string>("image", Convert.ToString(imagen)));
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("MyURL.domain/function", content);
var responseString = await response.Content.ReadAsStringAsync();
}
}
EDITED: My problem now is my server don't get the image. The django code is:
if request.method == 'POST':
form = RestrictedFileField(request.POST, request.FILES)
token = models.UsuarioHasToken.objects.get(token=parameters['token'])
user = token.user
print (request.FILES['image'])
user.image = request.FILES['image']
I can't modify the django code because this code it's working with Android app
Using this response ,
How to upload file to server with HTTP POST multipart/form-data
Try with this...
HttpClient httpClient = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
form.Add(new StringContent(token), "token");
var imageForm = new ByteArrayContent(imagen, 0, imagen.Count());
imagenForm.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
form.Add(imagenForm, "image", "nameholder.jpg");
HttpResponseMessage response = await httpClient.PostAsync("your_url_here", form);
response.EnsureSuccessStatusCode();
httpClient.Dispose();
string result = response.Content.ReadAsStringAsync().Result;