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().
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 trying to send a json object with a base4 encoded file to a web api service using the code below
MemoryStream target = new MemoryStream();
q.fileUpload.InputStream.CopyTo(target); //q.fileUpload is an HttpPostedFilebase pdf
var myfile= Convert.ToBase64String(target.ToArray());
var requestbody = new {
filedata = new
{
mimetype = "application/pdf",
basedata = "base64-data=" + myfile
}
};
var jsondata = JsonConvert.SerializeObject(requestbody );
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://web.base.url/");
client.DefaultRequestHeaders.Add("X-API-KEY", "SOMEAPIKEY");
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "upload");
request.Content = new StringContent(jsondata, Encoding.UTF8, "application/json");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var responsetask= client.SendAsync(request);
return Json(responsetask);
But i everytime i call this i get a 406 Not Acceptable response. Anyone knows what causes it?
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.
How to make xml content compatible with HttpClient's PostAsync operation for the content and where do you specify the headers for Content-Type = application/xml.
Error -> Cannot convert string to HttpContent
public async Task GetCustomersAsync(string firstname, string lastname)
{
using (var client = new HttpClient())
{
var content = "<soapenv:Envelope xmlns:xsi...";
var response = await client.PostAsync("https://domain.com/scripts/WebObj.exe/Client.woa/2/ws/ABC", content);
var responseString = await response.Content.ReadAsStringAsync();
}
}
My guess is what you want to do is the following:
public async Task<string> GetCustomersAsync(string firstname, string lastname)
{
using (var client = new HttpClient())
{
var content = new StringContent("<soapenv:Envelope xmlns:xsi...", Encoding.UTF8, "application/xml");;
var response = await client.PostAsync("https://example.com/scripts/WebObj.exe/Client.woa/2/ws/ABC", content);
return await response.Content.ReadAsStringAsync();
}
}
OR
using (var request = new HttpRequestMessage { RequesteUri = new Uri("POST_URL"), Method = HttpMethod.Post })
{
var content = new StringContent("<soapenv:Envelope xmlns:xsi...");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xml");
}
You can refer here to more information about other Content types that can be created and passed.
To specifically request xml content in response you must define the content type in the header of the content. The MediaTypeHeaderValue is parsed and set in the ContentType property of the content Headers. Here is a complete example of the code;
using (var client = new HttpClient())
{
var content = new StringContent(messageToPOST, Encoding.UTF8, "text/xml");
content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/xml");
response = await client.PostAsync(_uri, content);
responseMsg = await response.Content.ReadAsStringAsync();
}
The responseMsg property returned by the request as the response can be parsed as a string and otherwise converted to and validated as xml using an expression such as
XDocument xdoc = XDocument.Parse(responseMsg);
string xmlAsString = xdoc.ToString();
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);