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.
Related
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);
I have the following problem.
I have the method that sends json via POST:
public string request (string handler, string data)
{
WebRequest request = WebRequest.Create(baseUri + "/?h=" + handler);
request.Method = "POST";
request.ContentType = "text/json";
string json = "json=" + data;
byte[] bytes = Encoding.ASCII.GetBytes(json);
request.ContentLength = bytes.Length;
Stream str = request.GetRequestStream();
str.Write(bytes, 0, bytes.Length);
str.Close();
WebResponse res = request.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
lastResponse = sr.ReadToEnd();
return lastResponse;
}
When using the method on the server does not come data in POST. As if this code is not executed.
Stream str = request.GetRequestStream();
str.Write(bytes, 0, bytes.Length);
str.Close();
On the server i'm using following php script for debug:
<?php print_r($_POST); ?>
Also tried to write to the stream as follows:
StreamWriter strw = new StreamWriter(request.GetRequestStream());
strw.Write(json);
strw.Close();
The result - a zero response. In response comes an empty array.
The Problem is, that PHP does not "recognize" the text/json-content type. And thus does not parse the POST-request-data. You have to use the application/x-www-form-urlencoded content-type and secondly you have to encode the POST-data properly:
// ...
request.ContentType = "application/x-www-form-urlencoded";
string json = "json=" + HttpUtility.UrlEncode(data);
// ...
If you intend to supply the JSON-data directly you can leave the content-type to text/json and pass the data directly as json (without the "json=" part):
string json = data;
But in that case you have to change your script on the PHP-side to directly read the post data:
// on your PHP side:
$post_body = file_get_contents('php://input');
$json = json_decode($post_body);
Have you thought about using WebClient.UploadValues. Using the NameValueCollection with "json" as the name and JSON data string as the value?
This seems like the easiest way to go. Don't forget you can always add headers and credentials to the WebClient.
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.
I have a problem with posting of binary data to server via HttpWebRequest. Here is my client code:
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.UserAgent = RequestUserAgent;
request.ContentType = "application/x-www-form-urlencoded";
var responseStr = "";
var dataStr = Convert.ToBase64String(data);
var postData = Encoding.UTF8.GetBytes(
string.Format("uploadid={0}&chunknum={1}&data={2}", uploadId, chunkNum, dataStr));
using (var dataStream = request.GetRequestStream())
{
dataStream.Write(postData, 0, postData.Length);
dataStream.Close();
}
And then I want to work with request via MVC controller, here is it's signature:
public ActionResult UploadChunk(Guid? uploadID, int? chunkNum, byte[] data)
But I have error here, saying that data is not Base64 coded array, what am I doing wrong?
You need to escape the + characters in your Base64 by calling Uri.EscapeDataString.
This is driving me nuts:
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = Encoding.UTF8.GetByteCount(data);
Stream reqs = request.GetRequestStream();
StreamWriter stOut = new StreamWriter(reqs, Encoding.UTF8);
stOut.Write(data);
stOut.Flush();
I get an exception that I've run out of bytes in the stream...but I've used the same encoding to get the byte count!
Using ASCII this doesn't fail.
Is this because of the UTF-8 BOM that Windows likes to add in?
This is probably the BOM; try using an explicit encoding without a BOM:
Encoding enc = new UTF8Encoding(false);
...
request.ContentLength = enc.GetByteCount(data);
...
StreamWriter stOut = new StreamWriter(reqs, enc);
Even easier; switch to WebClient instead and of trying to handle it all yourself; it is very easy to post a form with this:
using (var client = new WebClient())
{
var data = new NameValueCollection();
data["foo"] = "123";
data["bar"] = "456";
byte[] resp = client.UploadValues(address, data);
}
Or with the code from here:
byte[] resp = client.Post(address, new {foo = 123, bar = 546});
You can also try something like this:
byte[] bytes = Encoding.UTF8.GetBytes(data);
request.ContentLength = bytes.Length;
request.GetRequestStream().Write(bytes, 0, bytes.Length);
Don't forget to actually URL-encode the data, like you promised in the ContentType. It's a one-liner:
byte[] bytes = System.Web.HttpUtility.UrlEncodeToBytes(data, Encoding.UTF8);