Multiple problems with HttpWebResponse - c#

So I am trying to create a simple class which I could use to consume REST web services. However I am having some troubles with HttpWebRequest object. Here is my code:
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace RichardKnop.Utils
{
public class REST
{
public void POST(string Uri)
{
}
public void GET(string Uri)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
// Set some reasonable limits on resources used by this request
request.MaximumAutomaticRedirections = 4;
request.MaximumResponseHeadersLength = 4;
// Set credentials to use for this request.
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine("Content length is {0}", response.ContentLength);
Console.WriteLine("Content type is {0}", response.ContentType);
// Get the stream associated with the response.
Stream receiveStream = response.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
Console.WriteLine("Response stream received.");
Console.WriteLine(readStream.ReadToEnd());
response.Close();
readStream.Close();
}
}
}
However I am getting several errors - for example:
Error 4 'System.Net.HttpWebRequest' does not contain a definition for 'GetResponse' and no extension method 'GetResponse' accepting a first argument of type 'System.Net.HttpWebRequest' could be found (are you missing a using directive or an assembly reference?) C:\Users\Richard\Documents\Visual Studio 2010\Projects\RichardKnop\RichardKnop\Utils\REST.cs 31 65 RichardKnop
How is that possible that it does not contain definition of the GetResponse method when I can clearly see in the documentation that it does have a method like that? Here it is:
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse.aspx
Sorry if this is something trivial but I am new to .NET.

As far as i know Silverlight allows only asynchronous calls
try using BeginGetResponse. MSDN link

Related

HttpException Request Time out

i can past this url into my browser and get the server time, https://api.binance.je/api/v3/time
But i am unable to get a response using below code. How can i debug this
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// Create a request for the URL.
WebRequest request = WebRequest.Create("https://api.binance.je/api/v3/time");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(response.StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
}
}
}
I see that you are able to retrieve the json data from the website. Tested this on my side.
However if you are trying to get the value only you need to read the json string (responsefromServer). This can be done by using a nuget pakage called Newtonsoft.
Then you will have to add the following to your code.
Above namespace:
using Newtonsoft.Json.Linq;
In main function before closing reader enz:
//Create jsonObject object from the api call response
JObject jObject = JObject.Parse(responseFromServer);
//Read propertie called serverTime and convert this to string to match variabele set
string time = jObject["serverTime"].ToString();
//Write the given time
Console.WriteLine(time);
Your code will look like the following:
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net;
namespace StackOverflow
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
// Create a request for the URL.
WebRequest request = WebRequest.Create("https://api.binance.je/api/v3/time");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(response.StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
//Create jsonObject object from the api call response
JObject jObject = JObject.Parse(responseFromServer);
//Read propertie called serverTime and convert this to string to match variabele set
string time = jObject["serverTime"].ToString();
//Write the given time
Console.WriteLine(time);
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
}
}
}
The problem was down to my vpn. Even though i didnt have an active connection. I killed the background service and restarted it and is now working
Similar issue
httpclient-getasync-times-out-when-connected-to-vpn

'HttpWebRequest' does not contain a definition for 'GetResponseAsync'

I am new in xamarin and visual studio,I have followed this tuto from microsoft:
enter link description here
to create a cross platform application,but I get this error:
'HttpWebRequest' does not contain a definition for 'GetResponseAsync' and no extension method 'GetResponseAsync' accepting a first argument of type 'HttpWebRequest' was found (a using directive or an assembly reference is it missing * ?)
and this is my code in which I get this error:DataService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using Newtonsoft.Json;
namespace shared
{
//This code shows one way to process JSON data from a service
public class DataService
{
public static async Task<dynamic> getDataFromService(string queryString)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(queryString);
var response = await request.GetResponseAsync().ConfigureAwait(false);
var stream = response.GetResponseStream();
var streamReader = new StreamReader(stream);
string responseText = streamReader.ReadToEnd();
dynamic data = JsonConvert.DeserializeObject(responseText);
return data;
}
}
}
Please how can I solve it, I checked the HttpWebRequest documentation but I didn't get well the problem
thanks for help
Not sure about HttpWebRequest - but a newer and now recommended way to get data is the following:
public static async Task<dynamic> getDataFromService(string queryString)
{
using (var client = new HttpClient())
{
var responseText = await client.GetStringAsync(queryString);
dynamic data = JsonConvert.DeserializeObject(responseText);
return data;
}
}
Try that and let me know if it works.

POST csv contents to HTTP API C#

Once again, I am new to C# and I am forcing myself through some exercises and putting the theory into practice. I am currently working on a small app to post the contents of a large csv file (2000+ lines) to a http API. The API is in the format
https://mydomain.com//api/dump/?
t = <app_token> // provided by auth function
&[
xml = <device_data_package>
OR
csv = <device_data_package>
My question is, how would i pass the csv contents to the body of the http POST? I appreciate your feedback and help.
Like other answers have said, assuming you have the code to open your file and read the contents, your CSV file will contain a string with values separated by commas. You can add it as a url parameter to give you something like this:
https://mydomain.com//api/dump/?t=my_token&csv=my,values,from,my,csv,file,go,here
However, there are limitations to the length of urls. So if you have anything other than a small CSV file, you are better off sending the CSV data as the body of the post, like you mention in your question.
The method below might come in handy. It takes an object as a parameter and embeds it into a post request and returns the response as a string. I have been using it on a site of mine to send data to an external service. It is part of a much bigger class, so I might have too many using statements.
You would use it like this:
WebUtilities.Post("https://mydomain.com//api/dump/?t=my_token", "csv=" + contents_of_my_csv_file);
The method looks like this:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Web.Script.Serialization;
using System.Xml;
public static class WebUtilities
{
public static string Post(string url, object postData)
{
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(url);
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, postData);
byte[] data = ms.ToArray();
httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
httpWReq.ContentLength = data.Length;
using (Stream newStream = httpWReq.GetRequestStream())
{
newStream.Write(data, 0, data.Length);
}
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
Stream stream = response.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader streamReader = new StreamReader(stream, encode);
string html = streamReader.ReadToEnd();
response.Close();
streamReader.Close();
return html;
}
}
The API should provide some specifications, but usually it'll just be one giant comma separated string like the following:
string foo = "bar1, bar2, bar3, soomanybars, notabar";

Get File Names from Web directory - from Services

Could you please let me know how can i fetch the file names from a web directory at a service level. I have a wrapper services. Inside it I am trying to fetch file names. I couldn't find a solution.
If I understand the question correctly, which I may not since you werent too specific, sounds as easy as getting FTP listing:
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{
public class WebRequestGetExample
{
public static void Main ()
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/");
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe#contoso.com");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
Console.WriteLine(reader.ReadToEnd());
Console.WriteLine("Directory List Complete, status {0}", response.StatusDescription);
reader.Close();
response.Close();
}
}
}

Problem Executing Async Web Request

Can anyone tell me what I've done wrong with this simple code?
When I run it it hangs on
using (Stream postStream = request.EndGetRequestStream(asynchronousResult))
If I comment out the requestState.Wait.WaitOne(); line the code executes correctly but obviously doesn't wait for the response. I'm guessing the the call to EndGetRequestStream is somehow returning me to the context of the main thread?? I'm pretty sure my code is essentially the same as the sample though (MSDN Documentation)
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Text;
namespace SBRemoteClient
{
public class JSONClient
{
public string ExecuteJSONQuery(string url, string query)
{
System.Uri uri = new Uri(url);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.Accept = "application/json";
byte[] requestBytes = Encoding.UTF8.GetBytes(query);
RequestState requestState = new RequestState(request, requestBytes);
IAsyncResult resultRequest = request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), requestState);
requestState.Wait.WaitOne();
IAsyncResult resultResponse = (IAsyncResult)request.BeginGetResponse(new AsyncCallback(GetResponseStreamCallback), requestState);
requestState.Wait.WaitOne();
return requestState.Response;
}
private static void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
try
{
RequestState requestState = (RequestState)asynchronousResult.AsyncState;
HttpWebRequest request = requestState.Request;
using (Stream postStream = request.EndGetRequestStream(asynchronousResult))
{
postStream.Write(requestState.RequestBytes, 0, requestState.RequestBytes.Length);
}
requestState.Wait.Set();
}
catch (Exception e) {
Console.Out.WriteLine(e);
}
}
private static void GetResponseStreamCallback(IAsyncResult asynchronousResult)
{
RequestState requestState = (RequestState)asynchronousResult.AsyncState;
HttpWebRequest request = requestState.Request;
using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult))
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader streamRead = new StreamReader(responseStream))
{
requestState.Response = streamRead.ReadToEnd();
requestState.Wait.Set();
}
}
}
}
}
}
couple of things:
I don't think you can re-use the same request object. i.e. you can call BeginGetRequestStream once per instance of HttpWebRequest.
if you want to perform two requests (calls to the server) you need two instances of HttpWebRequest one per request.
if you want synchronous behavior you have two options: Use the GetRespose method
or use begin/end in a synchronous way. to do so you don't need to pass a callback to the BeginGetRequestStream method (you can pass a null instead).
take the returned value from BeginGetRequestStream (IAsyncResult) and pass it to the EndGetRequestStream method:
AsyncResult resultRequest = request.BeginGetRequestStream(null, null);
Stream postStream = request.EndGetRequestStream(asynchronousResult)
EndGetRequestStream will block until the request is completed (this is bad if you are doing it from the UI, but it will still work).

Categories

Resources