Send umlauts in JSON using HTTPRequest - c#

I am trying to send a JSON string using POST to a web service running on Azure. The program is an app created with Xamarin Forms.
The JSON communication with the server basically works but I have problems with umlauts.
I have a class "Test"
public class Test
{
public string ä { get; set; }
}
which I try to serialize into a string. I use JsonConvert for this:
string postData = JsonConvert.SerializeObject(test);
This results in {"ä":"ä"}.
When I send this string I get a 400 Bad Request error message.
Interestingly, sending this string using the Firefox Plugin "Open HttpRequester" works perfectly.
Changing the first umlaut into "ae" ({"ae":"ä"}) works though.
Here the C# code I use for sending the string:
private void Send()
{
Uri uri = new Uri(serverPath);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/json";
request.BeginGetRequestStream(new AsyncCallback(UploadWithRequestStream), request);
}
private void UploadWithRequestStream(IAsyncResult asynchronousResult)
{
Test test = new Test();
test.ä = "ä";
string postData = JsonConvert.SerializeObject(test); // {"ä":"ä"}
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream uploadStream = request.EndGetRequestStream(asynchronousResult);
uploadStream.Write(byteArray, 0, postData.Length);
uploadStream.Flush();
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
// 404 Bad Request
}

Well, you've got a problem in this line:
uploadStream.Write(byteArray, 0, postData.Length);
You upload bytes from byteArray and count them as chars. But a single char (specifically, umlaut) could map to two bytes. In your example byteArray.Length = 11, and postData.Length = 9. That's why you send a shortened version of postData and it couldn't be processed by the server.
Replace the mentioned string with the string below and everything is fine:
uploadStream.Write(byteArray, 0, byteArray.Length);

Related

I got error 500 when I try to post a json to webservice

I'm developing an application in c# windows form , When I try to send a large json, I got an exception erro 500.
This the method to POST
public void POST(string url, string jsonContent)
{
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
request.Method = "POST";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(jsonContent);
request.ContentLength = byteArray.Length;
request.ContentType = "application/json";
using(Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
try
{
using(HttpWebResponse response = (HttpWebResponse) request.GetResponse())
{
length = response.ContentLength;
}
}
catch (WebException ex)
{
// Log exception and throw as for GET example above
}
}
I can send others object in JSON, but especially this object that has a large datas I get this exception .
But when I try to GET from webservice this same object it worked very well.
The problem is , I can get this large data but I can't send this same data.
Following the code of my controller.
[Route("reconhecimento")]
[HttpPost]
public bool PostPessoasReconhecimento([FromBody]PessoaReconhecimentoModel[] newpessoaReconhecimento)
{
PessoaReconhecimentoModel pessoaReconhecimento = new PessoaReconhecimentoModel();
return pessoaReconhecimento.postPessoaReconhecimento(newpessoaReconhecimento);
}
Joab i suppose the problem could be related to dimension of your request.
Try to check if your question could be classified as duplicate of that ones :
Maximum default POST request size of IIS 7 - how to increase 64kB/65kB limit?

Web Service call from Windows Phone

Good day to you all,
I wanted to ask you a simple question. What are the ways to call a soap web service from windows phone?
I have tried using the Service reference (I add service reference to a ?wsdl URL and it generates all the methods I have on web service), however I came across the error (unmarshalling error, unexpected elements) in sending the request. Just to note I have created a soap web service in Java and all of the methods are functioning and returning data, both in iOS application and in Android application, however I am struggling with this in windows phone.
I wanted to check some information of possibilities of calling and consuming a soap based web service in windows phone and examples if possible.
Thank you.
The method "Add Service Reference" always returns me following error:
Unmarshalling Error: unexpected element (uri:"http://webservicelocation.com/",local:"param1"). Expected elements are <{}param1>,<{}param2>,<{}param3>
You can use HttpWebRequest for calling a soap webservice.
Below code is used to do a currency converter which calls a soap based webservice.
Inside MainPage
ServiceConnection cs = new ServiceConnection();
Inside Constructor
string pXml = #"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:web=""http://www.webserviceX.NET/"">" +
"<soapenv:Header/><soapenv:Body><web:ConversionRate>" +
"<web:FromCurrency>" + "USD" + "</web:FromCurrency>" +
"<web:ToCurrency>" + "INR"+ "</web:ToCurrency>" +
"</web:ConversionRate></soapenv:Body></soapenv:Envelope>";
ServiceConnection cs = new ServiceConnection();
cs.OnEndResponse += new ServiceConnection.OnServerEndResponse(serviceConnection_OnEndResponse);
cs.ServiceCall(pXml);
After the service Call u will get response inside the function
void serviceConnection_OnEndResponse(string response, int statusCode)
{
MessageBox.Show(response);
}
Here is the class Service Connection
class ServiceConnection
{
public string url = "";
private string postXml;
public delegate void OnServerEndResponse(string response, int statusCode);
public event OnServerEndResponse OnEndResponse;
public ServiceConnection()
{
url = "http://www.webservicex.net/CurrencyConvertor.asmx";
}
public void ServiceCall(string pxml)
{
postXml = pxml;
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "text/xml;charset=UTF-8";
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
}
void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
string postData = postXml;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
string Response = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
OnEndResponse(Response, Convert.ToInt32(response.StatusCode));
});
}
catch
{
OnEndResponse("", 500);
}
}

Sending HTTP POST Request with XML to a web service and reading response data in C# for windows 8 phone

I a newbie at windows 8 phone development. I want to send an aync HTTP POST Request to a PHP web service with some headers and XML in the request body.
Also, I want to read the response sent back by the PHP web service.
Please guide me, how can I achieve the above two stated things.
what I have tried until now i am giving below
// Main begins program execution.
public static void SendRequest()
{
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.CreateHttp("http://mytestserver.com/Test.php");
webRequest.Method = "POST";
webRequest.ContentType = "text/xml";
webRequest.Headers["SOURCE"] = "WinApp";
var response = await httpRequest(webRequest);
}
public static async Task<string> httpRequest(HttpWebRequest request)
{
string received;
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{
using (var responseStream = response.GetResponseStream())
{
using (var sr = new StreamReader(responseStream))
{
received = await sr.ReadToEndAsync();
MessageBox.Show(received.ToString());
}
}
}
return received;
}
I am able to send the request using the above code. I just need to know that how I can send the XML in the request body to my web service.
For Set a file, and receive a server Response, I use that for sending .csv files:
First I initialize a POST Request:
/// <summary>
/// Initialize the POST HTTP request.
/// </summary>
public void SentPostReport()
{
string url = "http://MyUrlPerso.com/";
Uri uri = new Uri(url);
// Create a boundary for HTTP request.
Boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.ContentType = "multipart/form-data; boundary=" + Boundary;
request.Method = "POST";
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), est);
allDone.WaitOne();
}
After initialized Request, I send the differents parts of my files (headers + content + footer).
/// <summary>
/// Send a File with initialized request.
/// </summary>
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
string contentType = "binary";
string myFileContent = "one;two;three;four;five;"; // CSV content.
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream memStream = request.EndGetRequestStream(asynchronousResult);
byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("\r\n--" + Boundary + "\r\n");
memStream.Write(boundarybytes, 0, boundarybytes.Length);
// Send headers.
string headerTemplate = "Content-Disposition: form-data; ";
headerTemplate += "name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: " + contentType + "\r\n\r\n";
string fileName = "MyFileName.csv";
string header = string.Format(headerTemplate, "file", fileName);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
memStream.Write(headerbytes, 0, headerbytes.Length);
byte[] contentbytes = System.Text.Encoding.UTF8.GetBytes(myFileContent);
// send the content of the file.
memStream.Write(contentbytes, 0, contentbytes.Length);
// Send last boudary of the file ( the footer) for specify post request is finish.
byte[] boundarybytesend = System.Text.Encoding.UTF8.GetBytes("\r\n--" + Boundary + "--\r\n");
memStream.Write(boundarybytesend, 0, boundarybytesend.Length);
memStream.Flush();
memStream.Close();
allDone.Set();
// Start the asynchronous operation to get the response
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
And, Finnaly, I get The response server response, indicate the file is transmetted.
/// <summary>
/// Get the Response server.
/// </summary>
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
try
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd(); // this is a response server.
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
}
catch (Exception ex)
{
// error.
}
}
This sample works on Windows Phone 7 and Windows Phone 8.
This is for send a .csv content. You can adapt this code for send Xml content.
Replace just
string myFileContent = "one;two;three;four;five;"; // CSV content.
string fileName = "MyFileName.csv";
by your XML
string myFileContent = "<xml><xmlnode></xmlnode></xml>"; // XML content.
string fileName = "MyFileName.xml";
If all you're looking to do is take XML you've already generated and add it to your existing request as content, you'll need to be able to write to the request stream. I don't particularly care for the stock model of getting the request stream, so I'd recommend the following extension to make your life a little easier:
public static class Extensions
{
public static System.Threading.Tasks.Task<System.IO.Stream> GetRequestStreamAsync(this System.Net.HttpWebRequest wr)
{
if (wr.ContentLength < 0)
{
throw new InvalidOperationException("The ContentLength property of the HttpWebRequest must first be set to the length of the content to be written to the stream.");
}
var tcs = new System.Threading.Tasks.TaskCompletionSource<System.IO.Stream>();
wr.BeginGetRequestStream((result) =>
{
var source = (System.Net.HttpWebRequest)result.AsyncState;
tcs.TrySetResult(source.EndGetRequestStream(result));
}, wr);
return tcs.Task;
}
}
From here, augment your SendRequest method:
public static void SendRequest(string myXml)
{
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.CreateHttp("http://mytestserver.com/Test.php");
webRequest.Method = "POST";
webRequest.Headers["SOURCE"] = "WinApp";
// Might not hurt to specify encoding here
webRequest.ContentType = "text/xml; charset=utf-8";
// ContentLength must be set before a stream may be acquired
byte[] content = System.Text.Encoding.UTF8.GetBytes(myXml);
webRequest.ContentLength = content.Length;
var reqStream = await webRequest.GetRequestStreamAsync();
reqStream.Write(content, 0, content.Length);
var response = await httpRequest(webRequest);
}
If the service you're trying to reach is a SOAP service, you could simplify this a bit more by having the IDE generate a client class for you. For more information on how to do that, check out this MSDN article. However, if the service does not have a Web Service Definition Language (WSDL) document, this approach will not be able to assist you.
You can use the HTTP Client libraries in Windows Phone 8 and use the client in the same way that Windows 8.
First, get the HTTP Client Libraries from Nuget.
And now, to perform a POST call
HttpClient client = new HttpClient();
HttpContent httpContent = new StringContent("my content: xml, json or whatever");
httpContent.Headers.Add("name", "value");
HttpResponseMessage response = await client.PostAsync("uri", httpContent);
if (response.IsSuccessStatusCode)
{
// DO SOMETHING
}
i hope this helps you :)
I have solved the problem in some other way..
class HTTPReqRes
{
private static HttpWebRequest webRequest;
public static void SendRequest()
{
webRequest = (HttpWebRequest)HttpWebRequest.CreateHttp("https://www.mydomain.com");
webRequest.Method = "PUT";
webRequest.ContentType = "text/xml; charset=utf-8";
webRequest.Headers["Header1"] = "Header1Value";
String myXml = "<Roottag><info>test</info></Roottag>";
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(myXml);
webRequest.ContentLength = byteArray.Length;
// start the asynchronous operation
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
//webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
private static void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
Stream postStream = request.EndGetRequestStream(asynchronousResult);
String myXml = <Roottag><info>test</info></Roottag>";
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(myXml);
// Write to the request stream.
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the asynchronous operation to get the response
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
System.Diagnostics.Debug.WriteLine(responseString);
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
}
}
This perfectly solves my problem, send an XML within the HTTP Request and in Response receive the XML from the web service.
I recommend using the RestSharp library. You can find a sample request here.
This is what I used. It's really simple, add WindowsPhonePostClient.dll to your References (if you can't, try unblock the file first by properties->unblock), then use this code:
private void Post(string YourUsername, string Password)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("User", YourUsername);
parameters.Add("Password", Password);
PostClient proxy = new PostClient(parameters);
proxy.DownloadStringCompleted += proxy_UploadDownloadStringCompleted;
proxy.DownloadStringAsync(new Uri("http://mytestserver.com/Test.php",UriKind.Absolute));
}
private void proxy_UploadDownloadStringCompleted(object sender,WindowsPhonePostClient.DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
MessageBox.Show(e.Result.ToString());
}
You need to create a reference to the webservice wsdl or you could try to do it manually as detailed here:
https://stackoverflow.com/a/1609427/2638872
//The below code worked for me. I receive xml response back.
private void SendDataUsingHttps()
{
WebRequest req = null;
WebResponse rsp = null;
string fileName = #"C:\Test\WPC\InvoiceXMLs\123File.xml"; string uri = "https://service.XYZ.com/service/transaction/cxml.asp";
try
{
if ((!string.IsNullOrEmpty(uri)) && (!string.IsNullOrEmpty(fileName)))
{
req = WebRequest.Create(uri);
//req.Proxy = WebProxy.GetDefaultProxy(); // Enable if using proxy
req.Method = "POST"; // Post method
req.ContentType = "text/xml"; // content type
// Wrap the request stream with a text-based writer
StreamWriter writer = new StreamWriter(req.GetRequestStream());
// Write the XML text into the stream
StreamReader reader = new StreamReader(file);
string ret = reader.ReadToEnd();
reader.Close();
writer.WriteLine(ret);
writer.Close();
// Send the data to the webserver
rsp = req.GetResponse();
HttpWebResponse hwrsp = (HttpWebResponse)rsp;
Stream streamResponse = hwrsp.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
rsp.Close();
}
}
catch (WebException webEx) { }
catch (Exception ex) { }
finally
{
if (req != null) req.GetRequestStream().Close();
if (rsp != null) rsp.GetResponseStream().Close();
}
}

Sending data to php from windows phone

I need to send some data from windows phone 7 to php page through POST method, I have the following code at wp7 side
public void SendPost()
{
var url = "http://localhost/HelpFello/profile.php";
// Create the web request object
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
// Start the request
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
MessageBox.Show("data sent");
}
void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
// Create the post data
// Demo POST data
string postData = "user_id=3&name=danish&email_id=mdsiddiquiufo&password=12345&phone_Number=0213&about_me=IRuel2&rating=5";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
// End the get response operation
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
var Response = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
}
catch (WebException e)
{
MessageBox.Show(e.ToString());
}
}
and following on my localhost, to send the data to database
<?php
require_once("constants.php");
$user_id = $_POST['user_id'];
$name = $_POST['name'];
$email_id = $_POST['email_id'];
$password = $_POST['password'];
$phone_number = $_POST['phone_number'];
$about_me = $_POST['about_me'];
$rating = $_POST['rating'];
$query="INSERT INTO profile(User_ID,Name,Email_ID,password,Phone_Number,About_Me,Rating) VALUES ({$user_id},'{$name}','{$email_id}','{$password}',{$phone_number}, '{$about_me}' , {$rating})";
mysql_query($query,$connection);
mysql_close($connection);
?>
When I run the code I have no errors it means code is working fine, but no data is inserted in the database.
I think there is a better way than HttpWebRequest. That is WebClient. You can change the method there and append data like you do in get string. key=value&key2=value then when you invoke that request and get the response try debugging and getting the output from VS or if that is difficult simply assign he string to a textblock in the code. You will get to know if that page has been ever executed or not.
A sample code :
WebClient wc = new WebClient();
wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
wc.Encoding = Encoding.UTF8;
Parameters prms = new Parameters();
prms.AddPair("email", email);
prms.AddPair("password", password);
wc.UploadStringAsync(new Uri(loginUrl), "POST", prms.FormPostData(), null);
private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
// e.Result will contain the page's output
}
// This is my Parameters and Parameter Object classes
public class Parameters
{
public List<ParameterObject> prms;
public Parameters()
{
prms = new List<ParameterObject>();
}
public void AddPair(string id, string val)
{
prms.Add(new ParameterObject(id, val));
}
public String FormPostData()
{
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < prms.Count; i++)
{
if (i == 0)
{
buffer.Append(System.Net.HttpUtility.UrlEncode(prms[i].id) + "=" + System.Net.HttpUtility.UrlEncode(prms[i].value));
}
else
{
buffer.Append("&" + System.Net.HttpUtility.UrlEncode(prms[i].id) + "=" + System.Net.HttpUtility.UrlEncode(prms[i].value));
}
}
return buffer.ToString();
}
}
public class ParameterObject
{
public string id;
public string value;
public ParameterObject(string id, string val)
{
this.id = id;
this.value = val;
}
}
First error: assuming that no error messages means success
Second error: gaping SQL injection holes
first fix: always assume queries will fail, and check for that condition:
$result = mysql_query($query) or die(mysql_error());
second fix: ditch the mysql_() functions and switch to PDO using prepared statements with placeholders. Boom. No more injection problems, and your code won't stop working on you when mysql_() is removed in a future PHP version.
ps..
3rd error: no quotes on your phone number value. So someone submits 867-5309, and you end up inserting -4442 because mysql saw it as two numbers being subtracted, not a string.

Help with simple restful post problem

I am new to restful services and I have been creating a series of simple console apps to better understand. I have a simlple service that I am trying to send data to but I keep getting a 400 bad request error. I know it has to be something simple I overlooked. Any help would be greatly appreciated. Thanks
//service contract
[OperationContract, WebInvoke(Method = "POST", UriTemplate = "Test")]
bool Test(string input);
//service
public bool Test(string input)
{
Console.Out.WriteLine("recieved [" + input + "]");
return true;
}
//host program
class Program
{
static void Main(string[] args)
{
Uri baseAddress = new Uri("http://localhost:8889/TestImage");
WebServiceHost host = new WebServiceHost(typeof(ImageTestService), baseAddress);
try
{
host.Open();
Console.Out.WriteLine("TestService hosted at {0}", baseAddress.ToString());
Console.Out.WriteLine("hit enter to terminate");
Console.In.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
finally
{
if (host.State == CommunicationState.Faulted)
host.Abort();
else
host.Close();
}
}
}
//client program
// Create the web request
Uri address = new Uri("http://localhost:8889/TestImage/Test");
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
// Set type to POST
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
StringBuilder data = new StringBuilder();
data.Append("input=" + HttpUtility.UrlEncode("12345"));
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
// Set the content length in the request headers
request.ContentLength = byteData.Length;
// Write data
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
postStream.Close();
}
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
}
Not sure that is answers your question - but I have an extension method I have been using for form post:
public static HttpWebResponse DoFormPost(this HttpWebRequest request, string postVals, int timeoutSeconds)
{
request.Method = "POST";
request.Timeout = timeoutSeconds * 0x3e8;
request.ContentType = "application/x-www-form-urlencoded";
request.AllowAutoRedirect = false;
byte[] bytes = Encoding.UTF8.GetBytes(postVals);
request.ContentLength = bytes.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(bytes, 0, bytes.Length);
}
return (HttpWebResponse)request.GetResponse();
}
Or since you tagged WCF, then there is also another similar question:
Getting an http 400 error on calling a restful wcf service using http post
Unfortunately, I'm not sure what's wrong with your code, it looks okay at first glance. I wonder if it's the UriTemplate that you're using. If your method is "Test" and the UriTemplate is "Test", you might need to call it with this URL (two "Test" strings):
Uri address = new Uri("http://localhost:8889/TestImage/Test/Test");
I believe the method name is part of the URL by default, so the template gets applied after that.
With HTTP errors, I use a tool called Fiddler to troubleshoot. If you can create a request that works with the Request Builder, it's just a matter of figuring out how to produce that request via your code.
The WCF service you are calling is expecting the string you are passing to be serialized in XML!
The following has worked for me in the past:
string body = "foo";
string postData = #"<string xmlns='http://schemas.microsoft.com/2003/10/Serialization/'><![CDATA[" + body + "]]></string>";

Categories