WebRequest with UTF8 - c#

I am seeing some inconsistencies (from server) when using WebRequest with non-English data.
String strData = "zéro";
// String strData = "zero"; // this works
request = WebRequest.Create("http://example.com");
request.Method = strMethod;
byte[] byteArray = Encoding.UTF8.GetBytes(strData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
((HttpWebRequest)request).UserAgent = "Sailthru API C# Client";
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
This is happening only when using C# while java and PHP one works as expected so, I think it may be related to the way I'm encoding the data.
Any suggestion what I'm doing wrong?
Thaks in advance.

It should be application/x-www-form-urlencoded;charset=utf-8 and your response should have a content-type: x;charset=utf-8 either.

Related

POST as UTF8 - German characters

I'm trying to send a post as UTF8 using JSON data, from what i can see I'm correctly converting to UTF8 but i still get the data interprited as the unicode code point:
param = "method=setCategories&s=101";
param += "method=setCategories&s=101;
var name = HttpUtility.UrlEncode("geschirrspüler");
param += "&categories[02][dummies]=name;
So at this point the post request is as follows:
method=setCategories&s=101&method=setCategories&s=101&categories[02][dummies]=geschirrsp%c3%bcler
I then further encode to a UTF8 byte array and send the data:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://xxx.de/xxx.php");
json = <JSONobject>(param)
req.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(json);
req.ContentLength = byteArray.Length;
req.ContentType = "application/x-www-form-urlencoded";
req.ServicePoint.Expect100Continue = false;
Stream requestStream = req.GetRequestStream();
requestStream.Write(byteArray, 0, byteArray.Length);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
StreamReader reader = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
json_data = reader.ReadToEnd();
So here's where the issue is, the return data on the request highlights the word geschirrspüler as being interprited as geschirrsp\u00fcler (the unicode).
Before going back to the guy that owns the web service and accusing him of interpriting it incorrectly on his side i want to ensure I'm definitly doing all that's neccesary to send correct UTF8 encoding for the ü character.
Thanks in advance.

(400) Bad Request, can't get response (Custom minecraft launcher)

I just can't seem to be able to post a JSON to the webpage https://authserver.mojang.com/authenticate and get a response.
when I post the JSON it just says
The remote server returned an error: (400) Bad Request
I've gone through many different scripts by others and created my own by converting the Java code to C#. Anyway, here's the code that has worked the best so far.
string authserver = "https://authserver.mojang.com/authenticate";
byte[] rawData = fs.GetBytes(**[JSON]**);
WebRequest request = WebRequest.Create(authserver);
request.ContentType = "application/json";
request.Method = "POST";
//request.ContentLength = rawData.LongLength;
WebResponse connection = request.GetResponse();
connection.ContentType = "application/json";
connection.ContentLength = rawData.LongLength;
Stream stream = connection.GetResponseStream();
stream.Write(rawData, 0, rawData.Length);
stream.Flush();
byte[] rawVerification = new byte[10000];
int count = stream.Read(rawVerification, 0, 10000);
Edit:
is it possible to do this code with webclient?
Edit:
it had an invalid input, the json didn't have the correct data needed
try this:
WebRequest request = WebRequest.Create (authserver);
request.Method = "POST";
string postData = "YourJSON";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
request.ContentType = "application/json";
request.ContentLength = byteArray.Length;
using(Stream s = request.GetRequestStream ()){
s.Write (byteArray, 0, byteArray.Length);
}
WebResponse response = request.GetResponse ();
using(var dataStream = response.GetResponseStream ()){
using(StreamReader reader = new StreamReader (dataStream)){
string responseFromServer = reader.ReadToEnd ();
}
}
response.Close();
Essentially You shouldn't call getResponse() before you submit your data

How to send an array of strings using WebRequest

I have a method in my controller that accepts an array of strings:
public async Task<HttpResponseMessage> PostData(string[] data)
The thing I want to send a request using a console app to my api, but Im getting a 404 response and its not reaching the controller:
WebRequest request = WebRequest.Create("http://localhost:1119/api/psr");
request.Method = "POST";
string num= "[ \"89\",\"21\" , \"2A,\" ]";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(num);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(data, 0, data.Length);
dataStream.Close();
WebResponse response = request.GetResponse();

C# Post JSON with Authentication Header

I have problem with post JSON with authentication/Authorization.. Below is my code.. opponent said that they didnt receive the header...and i have no idea why...
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(stringData);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(serverURL);
req.Method = "POST";
req.ContentType = "application/json";
req.ContentLength = data.Length;
req.Headers.Add("Authentication", merchantID);
req.Headers["Authentication"] = merchantID;
Stream newStream = req.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
string returnString = response.StatusCode.ToString();
i am writing some example code to attach header while you calling service...
hope it is needful...
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(stringData);
HttpWebRequest reqest = (HttpWebRequest)WebRequest.Create(serviceUri);
reqest.Headers.Add(LoginName,LoginName);
reqest.Headers.Add(AuthenticationKey,AuthenticationKey);
reqest.Headers.Add(SessionKey,SessionKey);
reqest.ContentType = "application/json";
Stream newStream = req.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
string returnString = response.StatusCode.ToString();
I cannot surely say where the problem is. It can be even on a server-side.
Recently I worked on a project with header authentication and I have noticed an interesting thing. My PHP server received these headers with 'HTTP_' prefix.
In other words, I was making a request like:
req.Headers.Add("Authentication", merchantID);
And received it on server this way:
echo $_SERVER['HTTP_Authentication'];
I have spent a bunch of time to find it out.
You, actually, can ask your opponent if any similar header is present or ask him to examine your requests better and give you a feedback.
Also, try using WebClient. Maybe, it will help.
Furthermore, it is much more convenient.
string data = "{\"a\": \"b\"}";
WebClient client = new WebClient();
client.Headers.Add("Content-Type", "application/json");
client.Headers.Add("Authentication", merchantID);
var result = client.UploadString(serverURL, "POST", data);

How to post non-standard XML with C#

I have utilities that post standard XML, but am faced with interacting with a server that requires something I'm not familiar with.
The expected XML format is like this:
"xmldata=<txn><element_1>element_1_value</element_1><element_2>element_2_value</element_2></txn>"
When I post using my standard method:
byte[] data = Encoding.ASCII.GetBytes(XDocumentToString(xml));
var client = new WebClient();
client.Headers.Add("Content-Type", "text/xml");
byte[] result = client.UploadData(new Uri(url), "POST", data);
string resultString = Encoding.ASCII.GetString(result);
return XDocument.Parse(resultString);
I get an error message about the XML not being formatted correctly.
When I use some stuff I've found:
var request = _requestFactory.CreateCreditCardSaleRequest(xmlStringFromAbove);
WebRequest webRequest = WebRequest.Create("https://domain.com/process_some_xml.do");
webRequest.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(request);
// Set the ContentType property of the WebRequest.
webRequest.ContentType = "text/xml; encoding='utf-8'";
// Set the ContentLength property of the WebRequest.
webRequest.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = webRequest.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
// dataStream.Close();
// Get the response.
WebResponse response = webRequest.GetResponse();
// Display the status.
var httpWebResponse = (HttpWebResponse) response;
Console.WriteLine(httpWebResponse.StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
the response seems to indicate success, but no response content as expected.
I suspect it has something to do with the "xmldata=" at the beginning of the request, but cannot be sure.
Any suggestions?
Judging from the xmldata=, it sounds like the API wants the data sent as form-urlencoded. I suggest trying this:
string dataStr = "xmldata=" + HttpUtility.UrlEncode(XDocumentToString(xml));
byte[] data = Encoding.ASCII.GetBytes(dataStr);
and this:
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

Categories