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);
Related
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.
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
I am trying to write a YouTube app for windows phone, and I stumbled upon some problems on the authentication side. For some reason the following code is not working properly,
string url = "https://accounts.google.com/o/oauth2/token?";
string postData = "code=" + str + "&client_id=*********.apps.googleusercontent.com&client_secret=*******&grant_type=authorization_code";
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(url);
byte[] data = Encoding.Unicode.GetBytes(postData);
httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
using (Stream stream =await httpWReq.GetRequestStreamAsync())
stream.Write(data, 0, data.Length);
HttpWebResponse response =(HttpWebResponse)(await httpWReq.GetResponseAsync());
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
I am fairly new to HttpWebRequest so probably I missed something, although I am getting a response:
Bad Request
To be specific it says that grant_type is missing although I am pretty sure that it is not, I did everything according to the documentation. What am I doing wrong ?
This will probably fix it
parameters.Append("code=" + str);
parameters.Append("&client_id=*****.apps.googleusercontent.com");
parameters.Append("&client_secret=*****");
parameters.Append("&redirect_uri=urn:ietf:wg:oauth:2.0:oob:auto");
parameters.Append("&grant_type=authorization_code");
string p_params = parameters.ToString();
byte[] p_data_params = Encoding.UTF8.GetBytes(p_params);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
request.Accept = "application/json";
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
Stream dataStream = await request.GetRequestStreamAsync();
dataStream.Write(p_data_params, 0, p_data_params.Length);
dataStream.Dispose();
HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();
Stream responseStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8);
string result = readStream.ReadToEnd();
Works fine for me.
Please refer to the below code. How can I test/debug, whether the below code worked correctly or not. It runs and there are no compilation/runtime errors.
The end result of the below code is to set one of the controls in the page, to hold the POST data from below code. However I haven't come that far yet.
protected override void OnInit(EventArgs e)
{
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "http://s.com/is/image/scom/2Peel";
byte[] data = encoding.GetBytes(postData);
// Prepare web request...
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://m.com/Confirm.aspx?ID=175");
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();
// Send the data.
newStream.Write(data, 0, data.Length);
newStream.Close();
}
Update 1: I tried to find out the response using below code, but the page doesn't load at all.
HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse();
Console.WriteLine("Content length is {0}", response.ContentLength);
Console.WriteLine("Content type is {0}", response.ContentType);
Use the GetResponse method of your HttpWebRequest object (which you named "myRequest").
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.