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);
}
Related
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
I'm stucked here at getting a WebResponse from HTTPWebRequest.
The WebRequest.GetResponse() Method throws a WebException
("500 Internal Server Error"). When i read the returned HTML it says:
HTTP 403: Forbidden ('_xsrf' argument missing from POST)
Anyone knows this Error or knows what Im doing wrong?
(Im trying to log in to a Website using POST)
EDIT:
My sourcecode:
private String GetLoginCookies(String pHTTPurl, String pUserIDwithFormID, String pPasswordWithFormID)
{
String loginPageUrl = pHTTPurl;
CookieContainer cookieContainer = new CookieContainer();
var Request = (HttpWebRequest)WebRequest.Create(loginPageUrl);
Request.CookieContainer = cookieContainer;
Request.Method = "GET";
WebResponse Response = Request.GetResponse();
HttpWebResponse HttpResponse = Response as HttpWebResponse;
CookieCollection cookies = null;
if (HttpResponse != null)
{
//Cookies die benötigt werden um den Loginvorgang abzuschließen
cookies = HttpResponse.Cookies;
}
string formParams = string.Format(pUserIDwithFormID + "&" + pPasswordWithFormID);
Request = (HttpWebRequest)WebRequest.Create(loginPageUrl);
Request.CookieContainer = cookieContainer;
Request.UserAgent = "I am not a Bot! Ok maybe..";
WebResponse resp = null;
Request.ContentType = "application/x-www-form-urlencoded";
Request.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
Request.ContentLength = bytes.Length;
using (Stream os = Request.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
try
{
resp = Request.GetResponse();
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
String TestResponse = sr.ReadToEnd();
}
}
catch (WebException WE)
{
DebugConsole.AppendText("HTTP Error:" + WE.Message + Environment.NewLine);
String HTML = new StreamReader(WE.Response.GetResponseStream()).ReadToEnd();
DebugConsole.AppendText(HTML);
return null;
}
String cookieHeader = resp.Headers["Set-cookie"];
if (String.IsNullOrEmpty(cookieHeader))
return null;
else
return cookieHeader;
}
This is actually because the web method requires anti csrf (cross site request forgery, more info here: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)) validation parameter. What you can do, is to append the csrf value to the request header:
postHeaders.Add("X-CSRFToken", CSRF);
Maybe you can paste your source code here if you need any help with that, so we can look after it
OK! Solution found!
After getting the response of the Log-In site, search in the "Set-cookie" Header for _xsrf. This is the Token you have to put in the header of the next POST request.
I'm trying to call http://genderize.io/ , but i'm getting an error from .NET saying:
{"You must provide a request body if you set ContentLength>0 or SendChunked==true. Do this by calling [Begin]GetRequestStream before [Begin]GetResponse."}
How would I call this web service "http://api.genderize.io/?name=peter" from C# and get a JSON string back?
HttpWebRequest request;
string postData = "name=peter"
URL = "http://api.genderize.io/?"
Uri uri = new Uri(URL + postData);
request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
request.AllowAutoRedirect = true;
UTF8Encoding enc = new UTF8Encoding();
string result = string.Empty;
HttpWebResponse Response;
try
{
using (Response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = Response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
{
return readStream.ReadToEnd();
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Error: " + ex.Message);
throw ex;
}
You are making the call to the service using POST method, reading through the comments area in http://genderize.io/ the author states that only GET method requests are allowed.
Stroemgren: Yes, this is confirmed. Only HTTP GET request are allowed.
This answer probably would be better as a comment, but I don't have enough 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.
Help me please.
After sending post query i have webexception "Error getting response stream (ReadDone2): Receive Failure". help get rid of this error. thanks.
piece of code
try
{
string queryContent = string.Format("login={0}&password={1}&mobileDeviceType={2}/",
login, sessionPassword, deviceType);
request = ConnectionHelper.GetHttpWebRequest(loginPageAddress, queryContent);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())//after this line //occurs exception - "Error getting response stream (ReadDone2): Receive Failure"
{
ConnectionHelper.ParseSessionsIdFromCookie(response);
string location = response.Headers["Location"];
if (!string.IsNullOrEmpty(location))
{
string responseUri = Utils.GetUriWithoutQuery(response.ResponseUri.ToString());
string locationUri = Utils.CombineUri(responseUri, location);
result = this.DownloadXml(locationUri);
}
response.Close();
}
}
catch (Exception e)
{
errorCout++;
errorText = e.Message;
}
//Methot GetHttpWebRequest
public static HttpWebRequest GetHttpWebRequest(string uri, string queryContent)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Proxy = new WebProxy(uri);
request.UserAgent = Consts.userAgent;
request.AutomaticDecompression = DecompressionMethods.GZip;
request.AllowWriteStreamBuffering = true;
request.AllowAutoRedirect = false;
string sessionsId = GetSessionsIdForCookie(uri);
if (!string.IsNullOrEmpty(sessionsId))
request.Headers.Add(Consts.headerCookieName, sessionsId);
if (queryContent != string.Empty)
{
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
byte[] SomeBytes = Encoding.UTF8.GetBytes(queryContent);
request.ContentLength = SomeBytes.Length;
using (Stream newStream = request.GetRequestStream())
{
newStream.Write(SomeBytes, 0, SomeBytes.Length);
}
}
else
{
request.Method = "GET";
}
return request;
}
using (Stream newStream = request.GetRequestStream())
{
newStream.Write(SomeBytes, 0, SomeBytes.Length);
//try to add
newStream.Close();
}
In my case the server did not send a response body. After fixing the server, the "Receive Failure" vanished.
So you have two options:
Don't request a response stream, if you can live without it.
Make sure the server sends a response body.
E.g., instead of
self.send_response(200)
self.wfile.close()
the Python server code should be
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write("Thanks!\n")
self.wfile.close()
its not Xamarin or .NET's bug. :wink:
your server side endpoint fails when requesting. :neutral:
check your API endpoint if you own the api or contact support if you are getting API from third party company or service.
why it happens randomly : :wink:
because bug is in your inner if or loop blocks and it happens when it goes through this buggy loop or if.
best regards. :smile: