I am sending post request with pdf file attached example.pdf - this file is added to project in Visual Studio as "content". Problem is that I am receiving 400 Bad request.
API server is receiving (IFormFile uploadedFile) but in my case uploadedFile is null.
Authorization is good, url, headers also. I checked it via postman and it is working properly.
requestbody in debug mode is '{byte[63933]}'
How to solve this in C#?
string pathToPdfFile = "Scenarios\DefaultScenario\example.pdf";
byte[] requestBody = File.ReadAllBytes(pathToPdfFile);
public static string PostRequestUploadFile(string url, Dictionary<string, string> headersDictionary, byte[] requestbody)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
if (headersDictionary != null)
{
foreach (KeyValuePair<string, string> entry in headersDictionary)
{
request.Headers.Add(entry.Key, entry.Value);
}
}
request.ContentType = "application/pdf";
Stream dataStream = request.GetRequestStream();
byte[] byteArray = requestbody;
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
}
catch (Exception Ex)
{
return Ex.ToString();
}
}
I have made some changes
I added the Content Length header
You may have to change application/pdf to application/x-www-form-urlencoded
Finally, I don't know which parameters you are sending in headersDictionary, but may be missing the form 'file' field name
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST"; // Consider using WebRequestMethods.Http.Post instead of "POST"
if (headersDictionary != null){
foreach (KeyValuePair<string, string> entry in headersDictionary){
request.Headers.Add(entry.Key, entry.Value);
}
}
request.ContentType = "application/pdf";
// Dependending on your server, you may have to change
// to request.ContentType = "application/x-www-form-urlencoded";
byte[] byteArray = requestbody; // I don't know why you create a new variable here
request.ContentLength = byteArray.Length;
using (var dataStream = request.GetRequestStream()){
dataStream.Write(byteArray, 0, byteArray.Length);
}
using(var response = (HttpWebResponse)request.GetResponse()){
using(var reader = new StreamReader(response.GetResponseStream())){
return reader.ReadToEnd();
}
}
In my tests using this I have to use request.ContentType = "application/x-www-form-urlencoded" instead of PDF (I can't mock your entire setup)
As I don't have the server you are trying to send this and don't have the parameters I can't test this in your environment
For future reference, HttpWebRequest is a Legacy (obsolete) implementation that should be avoided and new implementations should use HttpClient read more
Related
I want to Pass XML string in HttpWebRequest Header?
my application in MVC4 .Net Framework 4.5 C#.
My code as below:
try
{
String requestXML = #"<REPORT>
<USER-DETAIL>
<NAME>ABC</NAME1>
<PASSWORD>12345</NAME2>
</USER-DETAIL>
</REPORT>";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.demoservice.com/service/getReport");
request.Accept = "application/xml";
request.Method = "POST";
request.Headers.Add("userId", "admin");
request.Headers.Add("password", "***");
request.Headers.Add("requestXml", requestXML);
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
String output = new StreamReader(responseStream).ReadToEnd();
Console.WriteLine(output);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
But I'm getting the following error,
Specified value has invalid CRLF characters. Parameter name: value
Please help, thanks in advance.
Do not add arbitrary data to the request headers. POST data should go in the request body. Request headers must conform to the HTTP spec, which the data you're erroneously trying to stuff in there doesn't.
This is how you should be doing it:
var data = Encoding.UTF8.GetBytes(requestXML);
request.ContentType = "application/xml";
request.ContentLength = data.Length;
using (var body = request.GetRequestStream())
{
body.Write(data, 0, data.Length);
}
I need help.
I have a method: PostCustomer
HttpResponseMessage PostCustomer([FromBody] CustomerRec Logs, [FromBody] Customer customer)
Now my problem is how will I able to test this through fiddler
I know I need to call for example:
"//api/customer/PostCustomer"
But how will I pass parameters on this?
I'm testing this using fiddler.
I'm not sure if you are asking how to build the url request (passing the parameters for your method through url)
If that's it, it should be like this
api/customer/PostCustomer/?FirstParameter=Example&SecondParemeter=Example2
If you mean the request itself
string postData = string.Format("?FirstParameter=" + txt_First.Text + "&SecondParemeter=" + txt_Last.Text);
byte[] data = Encoding.UTF8.GetBytes(postData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("..../api/customer/PostCustomer"/" + postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "application/json";
request.ContentLength = data.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(data, 0, data.Length);
}
try
{
using (WebResponse response = request.GetResponse())
{
var responseValue = string.Empty;
// grab the response
using (var responseStream = response.GetResponseStream())
{
using (var reader = new StreamReader(responseStream))
{
responseValue = reader.ReadToEnd(); // read the full response
}
}
if (responseValue != "")
{
//Do something here if response is not empty
}
}
}
catch (WebException ex)
{
// Handle error
}
PS: Can't comment on post because it asks for 50+ reputation...
I am trying to replicate a Couch database using .NET classes instead of a curl command line. I have never used WebRequest or Httpwebrequest before, but I am attempting to use them to make a post request with the script below.
Here is the JSON script for couchdb replication(I know this works):
{ ""_id"":"database_replicate8/7/12", "source":sourcedb, ""target"":"targetDB", ""create_target"":true, ""user_ctx"": { ""roles"": ["myrole"] } }
The above script is put into a text file, sourcefile.txt. I want to take this line and put it in a POST web request using .NET functionality.
After looking into it, I chose to use the httpwebrequest class. Below is what I have so far--I got this from http://msdn.microsoft.com/en-us/library/debx8sh9.aspx
HttpWebRequest bob = (HttpWebRequest)WebRequest.Create("sourceDBURL");
bob.Method = "POST";
bob.ContentType = "application/json";
byte[] bytearray = File.ReadAllBytes(#"sourcefile.txt");
Stream datastream = bob.GetRequestStream();
datastream.Write(bytearray, 0, bytearray.Length);
datastream.Close();
Am I going about this correctly? I am relatively new to web technologies and still learning how http calls work.
Here is a method I use for creating POST requests:
private static HttpWebRequest createNewPostRequest(string apikey, string secretkey, string endpoint)
{
HttpWebRequest request = WebRequest.Create(endpoint) as HttpWebRequest;
request.Proxy = null;
request.Method = "POST";
//Specify the xml/Json content types that are acceptable.
request.ContentType = "application/xml";
request.Accept = "application/xml";
//Attach authorization information
request.Headers.Add("Authorization", apikey);
request.Headers.Add("Secretkey", secretkey);
return request;
}
Within my main method I call it like this:
HttpWebRequest request = createNewPostRequest(apikey, secretkey, endpoint);
and I then pass my data to the method like this:
string requestBody = SerializeToString(requestObj);
byte[] byteStr = Encoding.UTF8.GetBytes(requestBody);
request.ContentLength = byteStr.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(byteStr, 0, byteStr.Length);
}
//Parse the response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
//Business error
if (response.StatusCode != HttpStatusCode.OK)
{
Console.WriteLine(string.Format("Error: response status code is{0}, at time:{1}", response.StatusCode, DateTime.Now.ToString()));
return "error";
}
else if (response.StatusCode == HttpStatusCode.OK)//Success
{
using (Stream respStream = response.GetResponseStream())
{
XmlSerializer serializer = new XmlSerializer(typeof(SubmitReportResponse));
reportReq = serializer.Deserialize(respStream) as SubmitReportResponse;
}
}
...
In my case I serialize/deserialize my body from a class - you will need to alter this to use your text file. If you want an easy drop in solution, then change the SerializetoString method to a method that loads your text file to a string.
Hello I try to write a HTTP Request in C# (Post), but I need help with an error
Expl: I want to send the Content of a DLC File to the Server and recive the decrypted content.
C# Code
public static void decryptContainer(string dlc_content)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://dcrypt.it/decrypt/paste");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII))
{
writer.Write("content=" + dlc_content);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Console.WriteLine(reader.ReadToEnd());
}
}
and here I got the html request
<form action="/decrypt/paste" method="post">
<fieldset>
<p class="formrow">
<label for="content">DLC content</label>
<input id="content" name="content" type="text" value="" />
</p>
<p class="buttonrow"><button type="submit">Submit ยป</button></p>
</fieldset>
</form>
Error Message:
{
"form_errors": {
"__all__": [
"Sorry, an error occurred while processing the container."
]
}
}
Would be very helpfull if someone could help me solving the problem!
You haven't set a content-length, which might cause issues. You could also try writing bytes directly to the stream instead of converting it to ASCII first.. (do it the opposite way to how you're doing it at the moment), eg:
public static void decryptContainer(string dlc_content)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://dcrypt.it/decrypt/paste");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
byte[] _byteVersion = Encoding.ASCII.GetBytes(string.Concat("content=", dlc_content));
request.ContentLength = _byteVersion.Length
Stream stream = request.GetRequestStream();
stream.Write(_byteVersion, 0, _byteVersion.Length);
stream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Console.WriteLine(reader.ReadToEnd());
}
}
I've personally found posting like this to be a bit "fidgity" in the past. You could also try setting the ProtocolVersion on the request.
I would simplify your code, like this:
public static void decryptContainer(string dlc_content)
{
using (var client = new WebClient())
{
var values = new NameValueCollection
{
{ "content", dlc_content }
};
client.Headers[HttpRequestHeader.Accept] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
string url = "http://dcrypt.it/decrypt/paste";
byte[] result = client.UploadValues(url, values);
Console.WriteLine(Encoding.UTF8.GetString(result));
}
}
It also ensures that the request parameters are properly encoded.
public string void decryptContainer(string dlc_content) //why not return a string, let caller decide what to do with it.
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://dcrypt.it/decrypt/paste");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";//sure this is needed? Maybe just match the one content-type you expect.
using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII))
{
writer.Write("content=" + Uri.EscapeDataString(dlc_content));//escape the value of dlc_content so that the entity sent is valid application/x-www-form-urlencoded
}
using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())//this should be disposed when finished with.
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
There could still be a problem with what is actually being sent.
One issue I see right away is that you need to URL encode value of the content parameter. Use HttpUtility.UrlEncode() for that.
Other than that there might be other issues there, but it is hard to say not knowing what service does. The error is too generic and could mean anything
request.ContentLength should be set as well.
Also, is there a reason you are ASCII encoding vs UTF8?
Get the stream associated with the response first then pass that into the Streamreader as below:
Stream receiveStream = response.GetResponseStream();
using (StreamReader reader = new StreamReader(receiveStream, Encoding.ASCII))
{
Console.WriteLine(reader.ReadToEnd());
}
As I can't comment on the solution of Jon Hanna. This solved it for me:
Uri.EscapeDataString
// this is what we are sending
string post_data = "content=" + Uri.EscapeDataString(dlc_content);
// this is where we will send it
string uri = "http://dcrypt.it/decrypt/paste";
// create a request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
// turn our request string into a byte stream
byte[] postBytes = Encoding.ASCII.GetBytes(post_data);
// this is important - make sure you specify type this way
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
// now send it
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
// grab te response and print it out to the console along with the status code
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine(new StreamReader(response.GetResponseStream()).ReadToEnd());
Console.WriteLine(response.StatusCode);
I am looking for an example of how, in C#, to put a xml document in the message body of a http request and then parse the response. I've read the documentation but I would just like to see an example if there's one available. Does anyone have a example?
thanks
private static string WebRequestPostData(string url, string postData)
{
System.Net.WebRequest req = System.Net.WebRequest.Create(url);
req.ContentType = "text/xml";
req.Method = "POST";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postData);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
using (System.Net.WebResponse resp = req.GetResponse())
{
if (resp == null) return null;
using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
{
return sr.ReadToEnd().Trim();
}
}
}
You should use the WebRequest class.
There is an annotated sample available here to send data:
http://msdn.microsoft.com/en-us/library/debx8sh9.aspx