encoding json using webrequest - c#

i am using this code to get json data
public static string GetAllScores(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
String errorText = reader.ReadToEnd();
}
throw;
}
}
the data is coming back and everything ok beside the data returning with é . i try lot of other users solution but nothing so far

Related

C# Post-Request Status 400 Bad Request

I am currently working on a C# Programm that is supposed to get Data from a REST API that I host.
The API requires a token for authentication which is returned from a POST request.
When I try to do the POST with C# I get a bad request (Status 400) but the GET request works fine. Now, My question is what I did wrong or what might be the cause for that error. When doing the request with postman both work perfectly.
The POST function:
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;
Console.WriteLine(response);
}
} catch (WebException ex) {
Console.WriteLine(ex);
}
}
The GET function:
string GET(string url) {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try {
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream()) {
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
return reader.ReadToEnd();
}
} catch (WebException ex) {
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream()) {
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}

How to get an Automation Account Webhook to Return Values in ASP.NET

I'm new to ASP.NET development and the use of webhooks.
I'm using ASP.NET and an Azure Automation Account which has a webhook. I can currently execute the webhook, however I would like to have my code wait until it receives the output of the webhook. How best to do this?
ASP.NET Code:
public ActionResult UpdateAll()
{
(random db calls)
string jsonList = JsonConvert.SerializeObject(userEnvironmentList);
try
{
string uri = "webhook_url";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
string data = jsonList;
request.Method = "POST";
request.ContentType = "text/plain;charset=utf-8";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] bytes = encoding.GetBytes(data);
request.ContentLength = bytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
request.BeginGetResponse((x) =>
{
using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(x))
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
String responseString = reader.ReadToEnd();
}
}
}, null);
}
catch (Exception ex)
{
throw ex;
}
return View();
}
PS in Automation Account:
param
(
[Parameter (Mandatory = $false)]
[object] $WebhookData
)
if ($WebhookData) {
return "Finally this works"
}
Call GetResponse in a synchronized context then.
Change ...
request.BeginGetResponse((x) =>
{
using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(x))
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
String responseString = reader.ReadToEnd();
}
}
}, null);
To ...
var response = (HttpWebResponse)webRequest.GetResponse();
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
String responseString = reader.ReadToEnd();
}
note: GetResponse() waits till the underlying web request finishes, then it returns the result. no need to use BeginGetResponse() in your code context.

Login into iCloud via Json Post request

I'm trying to log in into iCloud using a Json Post request in C#. Before trying to implement the code I was studying a little bit the iCloud requests using Chrome Console and using an Ad-on to replicate the requests in order to obtain the same result of the website.
First of All I checked the request directly from iCloud website:
And this is the response:
{
"serviceErrors" : [ {
"code" : "-20101",
"message" : "Il tuo ID Apple o la password non sono corretti."
} ]
}
Using "Advance REST Client" ad Chrome plugin to replicate the request I ve tried the same Json request to the same Url. But I get Empty response:
I Also tried to copy and paste the whole Header (All the settings) and than send the request but the response is the same:
Anyone has an Advice?
UPDATE: I tried to implement A Json request through c# program:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://idmsa.apple.com/appleauth/auth/signin");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{accountName: \"briesanji #gmail.com\", password: \"testPassword\", rememberMe: false, trustTokens: []}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
The problem is that Execution breaks when the
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
is hit and it gives me this error: System.Net.WebException: 'Error Remote Server: (400) Request not valid.'
UPDATE: I solved in this way:
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
}
}
string GET(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
Anyways I tested also the Answer and it was good to.. So I check it as valid thanks.
With this i dont get any error and the response content of the second request just tells me that there were too many failed logins for the test account...
private static void ICloud()
{
var cc = new CookieContainer();
var first = (HttpWebRequest)WebRequest.Create("https://idmsa.apple.com/appleauth/auth/signin?widgetKey=83545bf919730e51dbfba24e7e8a78d2&locale=de_DE&font=sf");
first.Method = "GET";
first.CookieContainer = cc;
var response1 = (HttpWebResponse)first.GetResponse();
using (var streamReader = new StreamReader(response1.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
var second = (HttpWebRequest)WebRequest.Create("https://idmsa.apple.com/appleauth/auth/signin");
second.ContentType = "application/json";
second.Method = "POST";
second.Accept = "application/json";
second.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
second.Referrer = "https://idmsa.apple.com/appleauth/auth/signin?widgetKey=83545bf919730e51dbfba24e7e8a78d2&locale=de_DE&font=sf";
second.Headers.Add("X-Requested-With", "XMLHttpRequest");
second.Headers.Add("X-Apple-Widget-Key", "83545bf919730e51dbfba24e7e8a78d2");
using (var streamWriter = new StreamWriter(second.GetRequestStream()))
{
string json = "{\"accountName\":\"test#icloud.com\",\"password\":\"test\",\"rememberMe\":false,\"trustTokens\":[]}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
try
{
var response2 = (HttpWebResponse)second.GetResponse();
using (var streamReader = new StreamReader(response2.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
catch(WebException we)
{
using (var r = new StreamReader(we.Response.GetResponseStream()))
{
var result2 = r.ReadToEnd();
}
}
}

Processing SOAP request with USING statement not working?

I'm trying to refactor a console app that uses SOAP to get some API data. I saw that the original code isn't using any USING statements. I thought I would try to refactor the code to do so, however, I get an "Internal Server Error". I've looked this over an few times and I'm not seeing why this wouldn't work. If I switch back to the original code it works as expected.
This is the original code that works:
public static string ProcessSOAPRequest(string xml, string endPoint)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(endPoint);
req.Timeout = 100000000;
req.Method = "POST";
Stream objStream = req.GetRequestStream();
doc.Save(objStream);
objStream.Close();
WebResponse resp = req.GetResponse();
objStream = resp.GetResponseStream();
StreamReader r = new StreamReader(objStream);
string data = r.ReadToEnd();
return data;
}
This is my attempt at refactoring with USING.
public static string ProcessSOAPRequest(string xml, string endPoint)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endPoint);
request.Timeout = 100000000;
request.Method = "POST";
using (WebResponse response = request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
UPDATE: another attempt based on the responses. This time in the second USING statement it says that I can't use stream = response.GetResponseStream(); because "stream" is in a using statement.
var data = string.Empty;
using (Stream stream = request.GetRequestStream())
{
doc.Save(stream);
using (WebResponse response = request.GetResponse())
{
stream = response.GetResponseStream();
using (StreamReader reader = new StreamReader(stream))
{
data = reader.ReadToEnd();
}
}
}
return data;
Answer to the update:
The variable declared in a using statement is treated as readonly. I suggest you to declare a new variable and assign the response to that. Why? - Why is a variable declared in a using statement treated as readonly?
var data = string.Empty;
using (Stream stream = request.GetRequestStream())
{
doc.Save(stream);
using (WebResponse response = request.GetResponse())
{
var responseStream = response.GetResponseStream();
if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream))
{
data = reader.ReadToEnd();
}
}
}
}
return data;
should work.

Downloading html source having SWF content using httpwebrequest or webclient

while downloading the html source code of http://www.orientalcuisines.in/ this site, In result I am getting only script data not whole html content,
I tried using webclient as well as httpwebrequest.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://" + website);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = null;
if (response.CharacterSet == null)
{
readStream = new StreamReader(receiveStream);
}
else
{
readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
}
string data = readStream.ReadToEnd();
response.Close();
readStream.Close();
}
OR
using (WebClient client = new WebClient())
{
client.DownloadFile(website);
}

Categories