I want to do a MultipartFormDataContent request. But I also want to pass a lot of params with it. When I'm just doing a post I do this:
public async Task<Webservice> inviteMembrs(List<KeyValuePair<string, string>> values)
{
String strUrl = String.Format("http://*****.com/nl/webservice/abc123/members/invite");
var http = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, new Uri(strUrl));
request.Content = new HttpFormUrlEncodedContent(values);
var result = await http.SendRequestAsync(request);
var data = new Webservice { Status = result.StatusCode };
if (result.StatusCode == Windows.Web.Http.HttpStatusCode.Ok && result.Content != null)
{
data.Data = await result.Content.ReadAsStringAsync();
Debug.WriteLine(data.Data);
}
return data;
}
This works perfect. But now I also want to pass an image with it.
I found a lot of examples but always without extra params.
Anyone can help?
Try the following code:
HttpClient httpClient = new HttpClient();
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StringContent(parameter), "name");
content.Add(new StreamContent(stream), "param", "filename");
HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(address, content);
Related
I am not getting any response - no error, no bad request status, etc. - when I send a post request to this API route. postData is simply a JSON object. The funny thing here is this: When i send post data as a string instead of an object, I can get a response.
View the code below:
[HttpPost]
[Route("api/updateStaffs/")]
public async Task<object> UpdateStaff([FromBody] object postData)
{
string _apiUrl = "http://localhost:5000/system/getToken";
string _baseAddress = "http://localhost:5000/system/getToken";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(_baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var responseMessage = await client.PostAsync(_apiUrl, new StringContent(postData.ToString(), Encoding.UTF8, "application/json"));
if (responseMessage.IsSuccessStatusCode)
{
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = responseMessage.Content;
return ResponseMessage(response);
}
}
return NotFound();
}
No response:
var postData = new {
user = "test"
pass = "hey"
};
var responseMessage = await client.PostAsync(_apiUrl, new StringContent(postData.ToString(), Encoding.UTF8, "application/json"));
OR
var responseMessage = await client.PostAsync(_apiUrl, new StringContent("{}", Encoding.UTF8, "application/json"));
Will get response:
var responseMessage = await client.PostAsync(_apiUrl, new StringContent("blahblah", Encoding.UTF8, "application/json"));
The receiving API is a third-party application so I am unable to verify if this error is on the other end.
Thanks.
If you dont want to use PostAsJsonAsync
You need to serialize your anonymous type to JSON, the most common tool for this is Json.NET
var jsonData = JsonConvert.SerializeObject(postData);
Then you need to construct a content object to send this data, here we can use ByteArrayContent but you can use a different type
var buffer = System.Text.Encoding.UTF8.GetBytes(jsonData);
var byteContent = new ByteArrayContent(buffer);
Then send the request
var responseMessage = await client.PostAsync(_apiUrl, byteContent);
Figured out the issue. Have to use HttpVersion10 instead of HttpVersion11.
I am doing a request through postman to a specific url but I set the form-data type in order to get data to the site like this:
Now I want to program this request inside C# but everything I tried so far is returning a 400 Bad Request response. This is what I tried:
public async Task<CheckAccessTokenModel> CheckAccessTokenAsync(string accessToken)
{
string uriString = "someurl";
var uri = new Uri(uriString);
try
{
using(var httpClient = new HttpClient())
{
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = uri
};
var ClientId = ConfigurationAccessor.Configuration["WebCredentials:ClientId"];
var Secret = ConfigurationAccessor.Configuration["WebCredentials:Secret"];
var authString = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{ClientId}:{Secret}"));
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authString);
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StringContent("token"), accessToken);
request.Content = content;
var response = await httpClient.SendAsync(request);
var checkTokenResponseData = await response.Content.ReadAsStringAsync();
//return new CheckAccessTokenModel { Active = true, Exp = 1647431224233 };
return JsonConvert.DeserializeObject<CheckAccessTokenModel>(checkTokenResponseData);
}
}
catch
{
return null;
}
}
I am doing it with the MultipartFormDataContent Object as suggested by many others here but it still won't work.
What can be the problem here?
EDIT: Wrong picture replaced
You can simply
request.Content = new StringContent($"token={accessToken}");
With form data I think it's something like this:
var data = new Dictionary<string, string>
{
{"token", acccessToken}
};
using var content = new FormUrlEncodedContent(data);
request.Content = content;
I'm trying send a JSON file with postman and it's working. But when I'm trying to send the same contents via HttpClient it's not working.
System.IO.File.WriteAllText(dirName + "\\importproduct.json", jsonitems);
var fileByteArray = File.ReadAllBytes(dirName + "\\importproduct.json");
using (var _client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
content.Add(new StreamContent(new MemoryStream(fileByteArray)), "file");
var url = $"{firmInfo.ServiceUrl}/product/api/products/import";
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearer_token.id_token);
var response = _client.PostAsJsonAsync(url, content).Result;
var result = response.Content.ReadAsStringAsync().Result;
}
}
PostMan:
Instead of using PostAsJsonAsync(); method you should use PostAsync(); So your code should be looking something like that
using (var _client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
content.Add(new StreamContent(new MemoryStream(fileByteArray)), "file");
var url = $"{firmInfo.ServiceUrl}/product/api/products/import";
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearer_token.id_token);
var response = _client.PostAsync(url, content).Result;
var result = response.Content.ReadAsStringAsync().Result;
}
}
PostAsJsonAsync method is a generic method, it expects as the second parameter the object that will be serialized and sent in the POST body.
var obj = JsonConvert.DeserializeObject<SomeModelClass>(jsonString);
var response = await _client.PostAsJsonAsync(url, obj).Result;
This is based on efecetir's post above. It works for me. BTW, I also upvoted his post.
My issue was I needed to set the content type at the content-based level.
var fileByteArray = File.ReadAllBytes(filePath);
HttpContent bytesContent = new ByteArrayContent(fileByteArray);
using (var httpClient = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
var RequestUri = new Uri($"http://whatever.com/");
//client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearer_token.id_token);
formData.Headers.Add("super-secret-key", "blah");
bytesContent.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
//httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //("multipart/form-data")); // Not needed
formData.Add(bytesContent, "file", "blah.json");
var response = httpClient.PostAsync(RequestUri, formData).Result;
return await HandleResponse(response);
}
Thanks for your comments.
I fixed it and convert my codes as below. Now it's working and much more clean.
HttpContent bytesContent = new ByteArrayContent(fileByteArray);
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
var url = $"{firmInfo.ServiceUrl}/product/api/products/import";
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearer_token.id_token);
formData.Add(bytesContent, "file", "importproduct.json");
var response = client.PostAsync(url, formData).Result;
var result = response.Content.ReadAsStringAsync().Result;
}
Here's code I'm using to post form information and a file
using (var httpClient = new HttpClient())
{
var surveyBytes = ConvertToByteArray(surveyResponse);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var byteArrayContent = new ByteArrayContent(surveyBytes);
byteArrayContent.Headers.ContentType = MediaTypeHeaderValue.Parse("text/csv");
var url = $"{firmInfo.ServiceUrl}/product/api/products/import";
var response = await httpClient.PostAsync(url , new MultipartFormDataContent
{
{byteArrayContent, "\"file\"", dirName + "\\importproduct.json"}
});
return response;
}
This is for .net 4.5.
I am using Windows.Web.Http instead of System and I am trying to send an image.
My sample code:
Dictionary<string, object> requestDictionary;
HttpClient httpClient = new HttpClient();
HttpRequestMessage re = new HttpRequestMessage();
HttpResponseMessage response;
re.Method = HttpMethod.Post;
re.RequestUri = url;
string content_type = "application/json";
string req_data = JsonConvert.SerializeObject(requestDictionary);
re.Content = new HttpStringContent(req_data, UnicodeEncoding.Utf8, content_type);
response = await httpClient.SendRequestAsync(re);
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
httpClient.Dispose();
httpClient=null;
In this case my requestDictionary will be some thing like
requestDictionary.Add("Image", filename);
requestDictionary.Add("description", some_description);
Someone please help me to achieve this.
By using .Net 4.5 (or by adding the Microsoft.Net.Http package from NuGet) there is an easier way to do this:
private string Upload(string actionUrl, string paramString, byte[] paramFileBytes)
{
HttpContent stringContent = new StringContent(paramString);
HttpContent bytesContent = new ByteArrayContent(paramFileBytes);
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(stringContent, "paramter");
formData.Add(bytesContent, "image");
var response = client.PostAsync(actionUrl, formData).Result;
if (!response.IsSuccessStatusCode)
{
return null;
}
return response.Content.ReadAsStringAsync().Result;
}
}
If you prefer to use a stream instead of a byte-array you can easily do this, by just using new StreamContent() instead of new ByteArrayContent().
I have got this HttpClient from Nuget.
When I want to get data I do it this way:
var response = await httpClient.GetAsync(url);
var data = await response.Content.ReadAsStringAsync();
But the problem is that I don't know how to post data?
I have to send a post request and send these values inside it: comment="hello world" and questionId = 1. these can be a class's properties, I don't know.
Update I don't know how to add those values to HttpContent as post method needs it. httClient.Post(string, HttpContent);
You need to use:
await client.PostAsync(uri, content);
Something like that:
var comment = "hello world";
var questionId = 1;
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("comment", comment),
new KeyValuePair<string, string>("questionId", questionId)
});
var myHttpClient = new HttpClient();
var response = await myHttpClient.PostAsync(uri.ToString(), formContent);
And if you need to get the response after post, you should use:
var stringContent = await response.Content.ReadAsStringAsync();
Try to use this:
using (var handler = new HttpClientHandler() { CookieContainer = new CookieContainer() })
{
using (var client = new HttpClient(handler) { BaseAddress = new Uri("site.com") })
{
//add parameters on request
var body = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("test", "test"),
new KeyValuePair<string, string>("test1", "test1")
};
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "site.com");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded; charset=UTF-8"));
client.DefaultRequestHeaders.Add("Upgrade-Insecure-Requests", "1");
client.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");
client.DefaultRequestHeaders.Add("X-MicrosoftAjax", "Delta=true");
//client.DefaultRequestHeaders.Add("Accept", "*/*");
client.Timeout = TimeSpan.FromMilliseconds(10000);
var res = await client.PostAsync("", new FormUrlEncodedContent(body));
if (res.IsSuccessStatusCode)
{
var exec = await res.Content.ReadAsStringAsync();
Console.WriteLine(exec);
}
}
}
Use UploadStringAsync method:
WebClient webClient = new WebClient();
webClient.UploadStringCompleted += (s, e) =>
{
if (e.Error != null)
{
//handle your error here
}
else
{
//post was successful, so do what you need to do here
}
};
webClient.UploadStringAsync(new Uri(yourUri), UriKind.Absolute), "POST", yourParameters);