Post in C# using HttpWebRequest with two parameters - c#

I am new in Programming. I am composing a straightforward application utilizing C# with android in which I need send information to server, information incorporates URL with two parameters. When I attempt to send information to server it just sends the URL however not parameters. Would you be able to help me with respect to this.
var postData = ("id1="+"123456");
postData += ("&id2="+"0123456789");
var request = (HttpWebRequest)WebRequest.Create("http://abc.xyz.com");
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST"
request.ContentType = "multipart/form-data";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
stream.Close();
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
response.Close();

You have set the content type to multipart/form-data but the data you are posting is formed as application/x-www-form-urlencoded.
A multipart content should look something like this:
--12345
Content-Disposition: form-data; name="sometext"
some text sent via post...
--12345--
And the content type must contain the boundary:
request.ContentType = "multipart/form-data; boundary=12345";
But you have this type of content:
id1=123456&id2=0123456789
So using application/x-www-form-urlencoded for the content type will solve the problem:
request.ContentType = "application/x-www-form-urlencoded";

Related

Is there a way to get XML content from an API in C#?

I created a Web API in C# to return XML document, actually there is a base url and I post something to it as body of a HttpWebRequest, and as a result, I will get response that is pure XML but as string.
So I need to send this response to client but the Content-Type of response is text/plain; charset=utf-8. It should be text/xml or application/xml, I've tried some xml parser like XDocument.Parse("myXml") and XElement.Parse("myXml"), but the type was 'text' and 'json'.
I also tried XmlSerializerOutputFormatter but at this moment the type gets correct but the body consists of other characters like this < should be '<' or &gt be '>':
<string><?xml version="1.0" encoding="UTF-8"?><wfs:FeatureCollection xmlns:ogc="http://www.opengis.net/ogc" ...</string>
Well this is my code on the API side:
public dynamic Get()
{
var request = (HttpWebRequest)WebRequest.Create(url);
var data = Encoding.ASCII.GetBytes(myData);
request.Method = "POST";
// request.ContentType = "application/xml; charset=UTF-8";
// request.Accept = "application/xml; charset=UTF-8";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
return responseString; // text type at postman app
return XDocument.Parse(responseString); // json type in Postman app
}

How do I send a POST request with a body that is a string or a character using httpwebrequest?

I have a Post call that takes a string GUID "AA0DB615-D4CB-4466-BC23-0E0083002220"
I am using HTTPWebRequest to send request but I am not sure how to add this along with my Post request. Basically I have not found any method inside the HTTPWebRequest to send a Post that is just a string or a character datatype. Is their anything like request.AddBody.
I have also looked at the GetResponseStream. Can I use this to write to the body as a string or character data type and send the call. I am stuck on this any help would be great
Here's a sample request that sends a plain text GUID in the body using HttpWebRequest, You can set the Content type to "text/plain" if you want to explicitly state that the content type is plain text :
var request = (HttpWebRequest)WebRequest.Create("URL GOES HERE");
request.Method = "POST";
var content = Guid.NewGuid().ToString(); //You should replace this with your GUID
var encoding = new ASCIIEncoding();
var bytes = encoding.GetBytes(content);
request.ContentType = "text/plain";
request.ContentLength = bytes.Length;
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
var response = request.GetResponse() as HttpWebResponse;
}

php can't receive request from C# webrequest when post data length more than 8K

I am trying to send base64 encoded data through C# WebRequest to php script. Then I receive sent data by file_get_contents("php://input"), when data length is lower than 8 KBs the php code is executed, otherwise it can't be executed. In the other hand php didn't receive the request.
the code C#:
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
// postData is Base64_encoded
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseData = reader.ReadToEnd();
responseData = SecurityUtils.DecryptUrlData(responseData);
reader.Close();
dataStream.Close();
response.Close();
return responseData;
Could any one help?
The below is incorrect (mea culpa). You cannot use enctype=multipart/form-data with php://input. See here
Perhaps you can post your PHP code into your question as well?
Make sure that when you POST from the c# app to your PHP app that you set the enctype to multipart/form-data.
Explanaition
Are you using application/x-www-form-urlencoded or multipart/form-data? There is a good explanation of the differenes here: application/x-www-form-urlencoded or multipart/form-data?
According to the link above, posting data in the application/x-form-urlencoded format will put the body into the URL. Many servers and languages (PHP, Apache) will cut off or throw errors when the URL is greater than 8K. See SO question: What is the maximum length for a URL?
Change the content type for the request
request.ContentType = "text/plain";
Check out php.iniĀ“s post_max_size on the server side

StreamSend API Blast, Sending Email

I need to use StreamSend API to send email, here is
StreamSend API Reference
I am making web request as post to following URL with proper credentials
https://app.streamsend.com/audiences/2/blasts.xml
StringBuilder sb = new StringBuilder();
sb.Append("https://app.streamsend.com/audiences/2/blasts.xml");
Uri uri = new Uri(sb.ToString());
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
request.ContentType = "application/xml";
StringBuilder strMail= new StringBuilder();
strMail.Append("<blast> ALL from api..... </blast>");
byte[] data = Encoding.ASCII.GetBytes(strMail.ToString());
Stream input = request.GetRequestStream();
input.Write(data, 0, data.Length);
input.Close();
HttpWebResponse nsResponse = (HttpWebResponse)request.GetResponse();
i am having err# 422 or 500. i would appreciate any help.
A couple of things. First, it looks like you're trying to do a POST request (you're sending data in the request stream). If you really want a POST request, you have to set request.Method = "POST";
Also, if you want an XML response, you need to set the Accept header. According to the documentation you listed, you need: request.Accept = "application/xml";
And you need to add your login id to the request, as well. I'm not sure how that's done. Perhaps in the request.Credentials property like this:
request.Credentials = new NetworkCredential("login_id", "your_key_here");
Finally, there's no reason to use StringBuilder if all you're doing is assigning strings. You can write, for example:
string urlString = "https://app.streamsend.com/audiences/2/blasts.xml"
Uri uri = new Uri(urlString);
or
byte[] data = Encoding.ASCII.GetBytes("<blast> ALL from api..... </blast>");

C# HttpWebRequest with XML Structured Data

I'm developing the client-side of a third party webservice. The purpose is that I send xml-file to the server.
How should I attach the xml-file to the httpwebrequest? What contentType is needed? More suggestions?
I cannot use mtom or dime.ie because I am using httpwebrequest. I am unable to use WCF either.
Here is a very basic method of sending XML structured data using HttpWebRequest (by the way you need to use request.ContentType = "application/xml";) :
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(myUrl));
request.Method = "POST";
request.ContentType = "application/xml";
request.Accept = "application/xml";
XElement redmineRequestXML =
new XElement("issue",
new XElement("project_id", 17)
);
byte[] bytes = Encoding.UTF8.GetBytes(redmineRequestXML.ToString());
request.ContentLength = bytes.Length;
using (Stream putStream = request.GetRequestStream())
{
putStream.Write(bytes, 0, bytes.Length);
}
// Log the response from Redmine RESTful service
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Logger.Info("Response from Redmine Issue Tracker: " + reader.ReadToEnd());
}
I use this at one of my projects (NBug) to submit an issue report to my Redmine issue tracker which accepts XML structured data over web requests (via POST). If you need further examples, you can get a couple of fully featured examples here: http://nbug.codeplex.com/SourceControl/list/changesets (click 'Browse' under 'Latest Verion' label on the right then navigate to "NBug\Submit\Tracker\Redmine.cs")

Categories