Posting a file with a raw XML using RestClient - c#

I've been using similar XML Posts with success....just that this one calls for ProofPDF which is a byte array.
How can I populate this XML Tag properly... I'm getting an invalid request at the moment.
public async void Post(List<IFormFile> files)
{
MemoryStream s = new MemoryStream();
files[0].CopyTo(s);
var client = new RestClient("https://api.2312312312dsa.com/default.asmx");
var request = new RestRequest();
request.AddHeader("SOAPAction", "http://api.giuhuiu.com/v20/LifelineStatus_Update");
request.AddHeader("Content-Type", " text/xml; charset=utf-8");
request.AddBody("<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body> <EP_Update xmlns=\"http://api.dddd23432.com\"><Request><Credentials><Username>dddd</Username><Password>dddd</Password><Client>test</Client></Credentials><CustomerID>1234454</CustomerID><Status>APPROVED</Status>"
+ "<ProofPDF>"+ s.ToArray()+"</ProofPDF>" //Here is the concerning code
+ "<Program>Apples</Program>"
+ "</Request></EP_Update></soap:Body></soap:Envelope>", "txt/xml");
var response = client.PostAsync(request);
var m = response.Result;
return;
}

Don't set the content type, read the docs, and use AddStringBody
request.AddStringBody(xmlString, "application/xml");
var response = await client.PostAsync(request);

Related

C# Converting string to JSON

I am trying to POST to using C# to a JSON payload which I can achieve but I am having trouble understanding how to replace the sample string with my own string.
From the code below you can see I have a string I want to send to my weblink. The code runs fine when I use "{\"text\":\"Hello, World!\"}" for the StringContent but if I try to replace it with the string of output_message it doesn't work. I am trying to work out how I convert my output_message to a format that JSON can recognize.
{
string output_message = "The file " + filename + " has been modified by " + user_modified + " and moved to the " + file_state + " file state. Please review the " + filename + " file and approve or reject.";
PostWebHookAsync(output_message);
Console.ReadLine();
}
static async void PostWebHookAsync(string Aoutput_message)
{
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "www.mywebsitelink"))
{
//request.Content = new StringContent("{\"text\":\"Hello, World!\"}", Encoding.UTF8, "application/json"); // - original do not delete
request.Content = new StringContent(Aoutput_message, Encoding.UTF8, "application/json");
var response = await httpClient.SendAsync(request);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Content);
}
}
}
I want to replace "{\"text\":\"Hello, World!\"}" with a string
To the best of my knowledge people are moving away from JavaScriptSerializer and towards Json.NET. It's even recommended in the documentation here
The corresponding Json.NET code would look something like:
static async void PostWebHookAsync(string output_message)
{
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "www.mywebsitelink"))
{
string jsonValue = JsonConvert.SerializeObject(new
{
text = output_message
});
request.Content = new StringContent(jsonValue, Encoding.UTF8, "application/json");
var response = await httpClient.SendAsync(request);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Content);
}
}
}
To use Json.NET you need to install the Newtonsoft.Json nuget package.
The best way is to create an object and serialize it.
To use JavaScriptSerializer you have to add a reference to System.Web.Extensions.dll
So for your problem, we create an anonymous object with a property text we pass the value Aoutput_message
static async void PostWebHookAsync(string Aoutput_message)
{
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "www.mywebsitelink"))
{
//request.Content = new StringContent("{\"text\":\"Hello, World!\"}", Encoding.UTF8, "application/json"); // - original do not delete
string jsonValue = new JavaScriptSerializer().Serialize(new
{
text = Aoutput_message,
});
request.Content = new StringContent(jsonValue, Encoding.UTF8, "application/json");
var response = await httpClient.SendAsync(request);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Content);
}
}
}
Examples

Cannot download a pdf with RestSharp?

I have been struggling to download a simple pdf hosted online using restsharp. I have been playing around with the code for over an hour and all I get are null object results.
The file downloads easily in POSTMAN using a GET and no content header set but still what gives?
Below is the noddy sandbox test I have been experimenting around with:
[TestFixture]
public class Sandbox
{
[Test]
public void Test()
{
var uri = "https://www.nlm.nih.gov/mesh/2018/download/2018NewMeShHeadings.pdf";
var client = new RestClient();
var request = new RestRequest(uri, Method.GET);
//request.AddHeader("Content-Type", "application/octet-stream");
byte[] response = client.DownloadData(request);
File.WriteAllBytes(#"C:\temp\1.pdf", response);
}
}
Update: Return a Stream
var baseUri = "https://www.nlm.nih.gov/mesh/2018/download/";
var client = new RestClient(baseUri);
var request = new RestRequest("2018NewMeShHeadings.pdf", Method.GET);
request.AddHeader("Content-Type", "application/octet-stream");
var tempFile = Path.GetTempFileName();
var stream = File.Create(tempFile, 1024, FileOptions.DeleteOnClose);
request.ResponseWriter = responseStream => responseStream.CopyTo(stream);
var response = client.DownloadData(request);
The stream is now populated with the downloaded data.
Try this:
var uri = "https://www.nlm.nih.gov/mesh/2018/download/";
var client = new RestClient(uri);
var request = new RestRequest("2018NewMeShHeadings.pdf", Method.GET);
//request.AddHeader("Content-Type", "application/octet-stream");
byte[] response = client.DownloadData(request);

Face API Base64 image post returns badrequest

Face API works with URL of the image but when I try to send image as
Base64 encoded it returns an error.
In this sample code I used Restsharp to send the data
My code is like below.
public string GenerateRest(String Base64Image)
{
var serviceURL = Constants.BaseServiceURI;
var client = new RestClient(serviceURL);
var request = new RestRequest(Constants.BaseResoruce, Method.POST);
request.AddHeader("Ocp-Apim-Subscription-Key", Constants.MS_API_KEY);
request.AddHeader("Content-Type", "application/octet-stream");
request.RequestFormat = DataFormat.Json;
var baseString = Base64Image.Replace("data:image/jpeg;base64,", String.Empty);
byte[] newBytes = Convert.FromBase64String(baseString);
request.AddBody(newBytes);
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
return content;
}
After fixing Restsharp request according to answer code is like
public FaceAPIOutput GenerateRest(String Base64Image)
{
var serviceURL = Constants.BaseServiceURI;
var client = new RestClient(serviceURL);
var baseString = Base64Image.Replace("data:image/jpeg;base64,", String.Empty);
byte[] newBytes = Convert.FromBase64String(baseString);
var request = new RestRequest(Constants.BaseResoruce, Method.POST);
request.AddHeader("Ocp-Apim-Subscription-Key", Constants.MS_API_KEY);
request.AddParameter("application/octet-stream", newBytes, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
return ConvertToFaceAPIOutObject(content);
}
Restsharp looks a bit idiosyncratic when taking a binary payload. Instead of request.AddBody, which adds a multipart form section, you need to do the following:
request.AddParameter("application/octet-stream", newBytes, ParameterType.RequestBody);
c.f. Can RestSharp send binary data without using a multipart content type?

Unable to get header "Content-Disposition" with httpclient in C#

SCENARIO:
First of all, please consider I'm using HttpClient class, not WebRequest, I know that there is a lot of related question here but all answers are for WebRequest.
I made a Web Api Application that set in this way the following header in order to download a .txt file:
resp.Content = new StringContent(result, System.Text.Encoding.UTF8, "text/plain");
resp.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = _datacontext.GetAppConfig("814FileNameHeader") + DateTime.Now.ToString("yyyyMMdd") + ".txt"
};
resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
After I made an HttpClient from other application to connect to this method.
Everything is working, retrieves 200 and the content of the file. But I can't get the header in order to read the filename.
TRIES MADE:
Working with a REST Client I can read the following header attribute:
Content-Disposition: attachment; filename=814Entes_PG_20160114.txt
and from the code I could debug it and I found that the header is in "invalidHeaders" but I can't reach the value:
QUESTION:
How can I set up this and getting without any doubt from the client?
UPDATE:
These are my tries to get the header:
The original:
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(uri);
string authentication = string.Concat(authenticationArgs[0], ":", authenticationArgs[1]);
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Basic " + Base64Encode(authentication));
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, "Report/" + type);
req.Content = new StringContent("");
HttpResponseMessage response = await httpClient.SendAsync(req);
Console.WriteLine(response.StatusCode);
if (response.IsSuccessStatusCode)
{
string stream = response.Content.ReadAsStringAsync().Result;
Console.Write("Respuesta servicio: " + stream);
Console.WriteLine(stream);
string cp = response.Headers.GetValues("Content-Disposition").ToString();
}
The second one I tried with some SO investigation:
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(uri);
string authentication = string.Concat(authenticationArgs[0], ":", authenticationArgs[1]);
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Basic " + Base64Encode(authentication));
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, "Report/" + type);
req.Content = new StringContent("");
HttpResponseMessage response = await httpClient.SendAsync(req);
Console.WriteLine(response.StatusCode);
if (response.IsSuccessStatusCode)
{
string stream = response.Content.ReadAsStringAsync().Result;
Console.Write("Respuesta servicio: " + stream);
Console.WriteLine(stream);
string cp = "";
HttpHeaders headers = response.Headers;
IEnumerable<string> values;
if (headers.TryGetValues("Content-Disposition", out values))
{
cp = values.ToString();
}
}
If you are trying to get the headers of the content, it should be from response.Content.Headers
As per #terbubbs you need response.Content.Headers.
But also code needs to be - for the first code sample:
string cp = response.Result.Content.Headers.GetValues("Content-Disposition").ToList()[0];
And for the second:
cp = values.FirstOrDefault().ToString();
Otherwise the result is System.String[]

Getting an XML sent by Webservice(POST method) in C# .NET

I am developing this application where I need to send an XML file to a webservice and read it from the webservice, and applying the business logic from the webservice, it will send an XML as response.
The thing is that I do know how to read the response the webservice sends, but I don't know how to retrieve the XML that the request sends to the webservice, the variable always comes null. If someone could help me out, I'd be really glad.
Request Method:
(...)
using (var client = new HttpClient())
{
var XMLRequest = Util.BuildXML.CreateRequestXML();
string url = string.Format(WEB_API_HOST + "/Application/MyMethod/");
HttpRequestMessage httpRequest = new HttpRequestMessage()
{
RequestUri = new Uri(url, UriKind.Absolute),
Method = HttpMethod.Post,
Content = new StringContent(XMLRequest.ToString(), Encoding.UTF8, "text/xml")
};
var task = client.SendAsync(httpRequest).ContinueWith((taskwithmsg) =>
{
var response = taskwithmsg.Result;
if (response.IsSuccessStatusCode)
{
var xmlResponse = response.Content.ReadAsStringAsync().Result;
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlResponse);
var test = doc.SelectSingleNode("RESPONSE/...").InnerText;
}
else
{
var contentTask = response.Content.ReadAsStringAsync().Result;
throw new Exception(contentTask);
}
});
task.Wait();
}
(...)
And the Webservice ( that is supposed to receive the XML and read it)
[AcceptVerbs("GET", "POST")]
public HttpResponseMessage MyMethod(XmlDocument doc)
{
// Any doc.SelectSingleNode() wouldn't work, the doc variable is null.
var response = new StringBuilder();
response.Append("<?xml version=\"1.0\" standalone=\"yes\"?>");
response.Append("<RESPONSE>");
(...)
response.Append("</RESPONSE>");
var xmlResponse = new HttpResponseMessage()
{
Content = new StringContent(response.ToString(), Encoding.UTF8, "text/xml")
};
return xmlResponse;
}
So how do I get to read the xml in the "MyMethod" method?
Thanks a bunch!

Categories