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
Related
I am trying to call API from windows forms its going in timeout. but its working fine from POSTMAN app.
I am using below code for calling web API from windows app.
public string ReadXMLResponse(string strrequestxml, string strTallyServer1)
{
string URL = strTallyServer1;
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(URL);
myHttpWebRequest.Accept = "application/xml";
myHttpWebRequest.ContentType = "application/xml";
myHttpWebRequest.Timeout = 60000;
string method = "POST";
myHttpWebRequest.Method = method;
if (method == "POST")
{
using (var streamWriter = new StreamWriter(myHttpWebRequest.GetRequestStream()))
{
streamWriter.Write(strrequestxml);
streamWriter.Flush();
}
}
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
using (var streamReader = new StreamReader(myHttpWebResponse.GetResponseStream()))
{
var streamRead = streamReader.ReadToEnd().Trim();
return streamRead;
}
return "";
}
I had the same code and the same problem. It was driving me crazy till I found something on one of Microsoft blogs. Tried to google the original page but I couldn't find it.
WebRequest request = WebRequest.Create("URL");
request.Method = "POST";
var postData = string.Format(dataFormnat, Uri.EscapeDataString(data.Serialize()));
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 responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
I'm doing a post request to several severs. These servers return all json except one. One of them returns data like this: 1fe2 80b9 0800 0000 0000 0400 c3ac c2bd.
If I do the same with a rest client I get from all servers valid Json but when I do it in c# one of the servers returns that kind of data.
I use the following code to do this:
public static string MakeRequest(string url, string requestBody, string methodName)
{
string result = "";
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/json";
result = client.UploadString(string.Format("{0}{1}", url, methodName), "POST", requestBody);
}
return result;
}
I also tried with this (old code):
public static string MakeRequestA(string url, string requestBody, string methodName)
{
byte[] postBytes = Encoding.ASCII.GetBytes(requestBody);
var request = (HttpWebRequest)WebRequest.Create(string.Format("{0}{1}", url, methodName));
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version11;
request.Method = "POST";
request.ContentType = "application/json";
request.Accept = "text/plain";
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
WebResponse response = request.GetResponse();
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
var dataStream = response.GetResponseStream ();
var reader = new StreamReader (dataStream);
string responseFromServer = reader.ReadToEnd ();
reader.Close ();
dataStream.Close ();
response.Close ();
return responseFromServer;
}
I can't really give you the server urls because they are private. Anybody a clue why I'm getting this data instead of valid json?
HI please install fiddler tool in your machine, and with that check the request header which generated by REST client. And capture the request header which generated by .net client. Then compare both request formats to find the solution
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();
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.
/*WebClient client = new WebClient();
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
string parameters = "code=4/f2PwqbN1Z5FpEEcT0scRH20B6d-F.ouqZIhzZqUYbEnp6UAPFm0EuJPwSigI&" +
"client_id=162438320977-ml14ajmuutlrr71maal933ma5cjolc8l.apps.googleusercontent.com&" +
"&client_secret=1IJxvSnmxcx-i2l_YGgYOD0i&redirect_uri=http://localhost&grant_type=authorization_code";
byte[] data = Encoding.UTF8.GetBytes(parameters);
var test = client.UploadData("http://accounts.google.com/o/oauth2/token","POST", data);
string result = data.ToString();*/
StringBuilder parameters = new StringBuilder();
parameters.Append("code=4/IoAJMoYxUqk7lkH_WbSr3lk4URf1.0t7Qx7qZE5QeEnp6UAPFm0G0EvMSigI");
parameters.Append("&client_id=162438320977-ml14ajmuutlrr71maal933ma5cjolc8l.apps.googleusercontent.com");
parameters.Append("&client_secret=1IJxvSnmxcx-i2l_YGgYOD0i");
parameters.Append("&redirect_uri=urn:ietf:wg:oauth:2.0:oob");
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";
request.ContentLength = p_data_params.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(p_data_params, 0, p_data_params.Length);
dataStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8);
string result = readStream.ReadToEnd();
The only approach that seems to work for me is using HttpWebRequest. I found the answer here: .Net Google OAuth token WebRequest Bad Request Protocol Error If anyone knows of a way to get the Web Client implementation working please let me know! Thanks.