Returning value from a method - c#

I have the following code:
public class Request
{
static string username = "ha#gmail.com";
public string Send()
{
///some variables
try
{
///
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream Data = response.GetResponseStream())
{
string text = new StreamReader(Data).ReadToEnd();
}
}
}
return text;
}
}
Getting an error: 'text' does' t exist in the current context. How to return the 'Text' value from the method.

public string Send()
{
//define the variable outside of try catch
string text = null; //Define at method scope
///some variables
try
{
///
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream Data = response.GetResponseStream())
{
text = new StreamReader(Data).ReadToEnd();
}
}
}
return text;
}

public string Send()
{
try {
return "Your string value";
}
catch (WebException e) {
using (WebResponse response = e.Response) {
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream Data = response.GetResponseStream())
{
return new StreamReader(Data).ReadToEnd();
}
}
}
}

You have to initialize variable before try clause to use it outside of try:
public string Send()
{
string text = null;
try
{
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream Data = response.GetResponseStream())
{
text = new StreamReader(Data).ReadToEnd();
}
}
}
return text;
}

You need to define text as a local variable in Send(), not inside a sublocal block like here inside using(...). Such it would be only valid there.

Related

Properly handle WebRequests

I have a dynamic page with a .JSON file, and I'm using my C# program to access it every x number of seconds, to determine if something has been changed or not. Everything works flawlessly as long as I have Internet connection, if for whatever reason I lose it, then my program crashes as the ex.Response is a null. I was wondering if there's a better way of handling the following code:
void Function(){
while(true){
jList = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<jsonList>(GET(jsonUrl));
//SOME THINGS I DO with the data above here
Thread.Sleep(5000);
}}
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;
if (ex.Response != null) {
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
}
throw;
}
}
Perhaps I should ping it first, and see if I get a reply, and only then Perform the WebRequest function?
EDIT:
After adding this
public bool getResponse(string URL)
{
try
{
WebClient wc = new WebClient();
string HTMLSource = wc.DownloadString(URL);
return true;
}
catch (Exception)
{
return false;
}
}
And use it as
void Function(){
while(true){
if (!getResponse(jsonUrl))
{
return;
}
jList = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<jsonList>(GET(jsonUrl));
//SOME THINGS I DO with the data above here
Thread.Sleep(5000);
}}
My C# application waits a bit, and then exits normally. Why?
The program '[10476] Kiosk2.vshost.exe' has exited with code 0 (0x0).
Alright, well this seems to work fine for me.
public void Update() //CALLED IT void FUNCTION earlier
{
while (true)
{
while (getResponse(jsonUrl))
{
jList = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<jsonList>(GET(jsonUrl));
//I DO SOME STUFF HERE
//INTERESTING STUFF
Thread.Sleep(5000);
}
}
}
And seconds function:
public bool getResponse(string URL)
{
try
{
WebClient wc = new WebClient();
string HTMLSource = wc.DownloadString(URL);
return true;
}
catch (Exception)
{
return false;
}
}

C# - HTTP request to get the initial page

I have to Send HTTP request to GET the initial page then, GET the HTTP response and do a check to see if it is a 200 response code. All this has to be saved into a .csv file, four times per website.
This is how far I got:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HTTPrequestApp
{
class Program
{
static void Main(string[] args)
{
var lstWebSites = new List<string>
{
"www.mearstransportation.com",
"www.amazon.com",
"www.ebay.com",
"www.att.com",
"www.verizon.com",
"www.sprint.com",
"www.centurylink.com",
"www.yahoo.com"
};
string filename = #"RequestLog.txt";
{
using (var writer = new StreamWriter(filename, true))
{
foreach (string website in lstWebSites)
{
for (var i = 0; i < 4; i++)
{
MyWebRequest request = new MyWebRequest();
request.Request();
}
}
}
}
}
}
}
I still have to do the GET request in another class I created called MyWebRequest.cs
Please help me.
In your MyWebRequest class do the following (you will also need to pass the website url string to the MyWebRequest, but I'll just do it explicitly):
HttpWebResponse response = null;
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.google.com/thisisadeadlink");
request.Method = "GET";
response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
Console.Write(sr.ReadToEnd());
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError)
{
response = (HttpWebResponse)e.Response;
Console.Write("Errorcode: {0}", (int)response.StatusCode);
}
else
{
Console.Write("Error: {0}", e.Status);
}
}
finally
{
if (response != null)
{
response.Close();
}
}
This should catch if server failed and response.StatusCode is not 200.
Since your MyWebRequest is using HttpWebRequest, the Request method can return HttpWebResponse if it has the URL as a parameter like this:
public class MyWebRequest
{
public HttpWebResponse Request(string url)
{
HttpWebResponse response = null;
try
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
response = (HttpWebResponse)httpWebRequest.GetResponse();
}
catch (WebException ex)
{
// Handle exception
}
return response;
}
}
and it can be called in the for loop like this:
HttpWebResponse response = request.Request("http://" + website);
if ((response != null) && (response.StatusCode == HttpStatusCode.OK))
{
// Write .csv file
}

C# HttpWebRequest.GetResponse encoding URL

I am using the C# HttpWebRequest.GetResponse with a URL that is not encoded. But when I inspect the request using fiddler I see that the URL is encoded. I wanted to confirm that HttpWebRequest Class is encoding the URL internally but could not find it in the documentation. Can someone point me to the documentation where i can find this or some other way to validate it?
KR
Here it is:
WebRequest.Create (you are using that method to create your HttpWebRequest object, right?) says "The Create method uses the requestUriString parameter to create a Uri instance that it passes to the new WebRequest"
https://msdn.microsoft.com/en-us/library/bw00b1dc(v=vs.110).aspx
The constructor for Uri (which is being called by the Create method) says it "parses the URI, puts it in canonical format, and makes any required escape encodings"
https://msdn.microsoft.com/en-us/library/z6c2z492(v=vs.110).aspx
//endpoint is url and method can be post or get... the below will help you to catch any errors from server..
make it a function so its wll be easy for you to use where ever you want ...
HttpWebRequest httpRequest = (HttpWebRequest)HttprequestObject(endpoints, method);
using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
{
streamWriter.Write(jsonObject);
streamWriter.Flush();
streamWriter.Close();
}
var result = "";
HttpWebResponse httpResponse;
try
{
httpResponse = (HttpWebResponse)httpRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
}
catch (WebException e)
{
Console.WriteLine("This program is expected to throw WebException on successful run." +
"\n\nException Message :" + e.Message);
if (e.Status == WebExceptionStatus.ProtocolError)
{
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
using (Stream data = e.Response.GetResponseStream())
using (var reader = new StreamReader(data))
{
string text = reader.ReadToEnd();
Console.WriteLine(text);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
or u want class and u want to use for creating api lib then just copy paste this class ..this is for c# but almost similer syntax for java ...
with this u can access any api or url or also used to pass json file to server ..
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace ExternalAPIs_SynapsePay.Helpers
{
class RESTHelpers
{
public dynamic APICalls(JObject jsonObject, string endpoints, string method)
{
HttpWebRequest httpRequest = (HttpWebRequest)HttprequestObject(endpoints, method);
using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
{
streamWriter.Write(jsonObject);
streamWriter.Flush();
streamWriter.Close();
}
var result = "";
HttpWebResponse httpResponse;
try
{
httpResponse = (HttpWebResponse)httpRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
}
catch (WebException e)
{
Console.WriteLine("This program is expected to throw WebException on successful run." +
"\n\nException Message :" + e.Message);
if (e.Status == WebExceptionStatus.ProtocolError)
{
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
using (Stream data = e.Response.GetResponseStream())
using (var reader = new StreamReader(data))
{
string text = reader.ReadToEnd();
Console.WriteLine(text);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return result;
//return "Success";
//not sure what to return
//here i have to add sql server code to enter into database
}
public HttpWebRequest HttprequestObject(string endpoints, string method)
{
string url = Setting.API_TEST_VALUE + endpoints;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = method;
return httpWebRequest;
}
/// <summary>
/// This method is useful when you have to pass JSON as string not as object... This is basically a constructor..
/// Even if u pass json object it will accept, so no need to worry about that.
/// </summary>
/// <param name="ljson"></param>
/// <param name="endpoints"></param>
/// <param name="method"></param>
/// <returns></returns>
public dynamic APICalls(string jsonString, string endpoints, string method)
{
HttpWebRequest httpRequest = (HttpWebRequest)HttprequestObject(endpoints, method);
using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
{
streamWriter.Write(jsonString);
streamWriter.Flush();
streamWriter.Close();
}
var result = "";
HttpWebResponse httpResponse;
try
{
httpResponse = (HttpWebResponse)httpRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
}
catch (WebException e)
{
Console.WriteLine("This program is expected to throw WebException on successful run." +
"\n\nException Message :" + e.Message);
if (e.Status == WebExceptionStatus.ProtocolError)
{
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
using (Stream data = e.Response.GetResponseStream())
using (var reader = new StreamReader(data))
{
string text = reader.ReadToEnd();
Console.WriteLine(text);
result = text;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return result;
//return "Success";
//not sure what to return
//here i have to add sql server code to enter into database
}
public void HttlpResponseObject(HttpWebRequest httpResponse)
{
var response = (HttpWebResponse)httpResponse.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
//entry into databse can be done from here
//or it should return some value
}
}
}

C# - Catch WebException While Posting XML Async

I am POSTING XML data using WebClient.
public string uploadXMLData(string destinationUrl, string requestXml)
{
try
{
System.Uri uri = new System.Uri(destinationUrl);
using (WebClient client = new WebClient())
{
client.Headers.Add("content-type", "text/xml");
var response = client.UploadString(destinationUrl, "POST", requestXml);
}
}
catch (WebException webex)
{
WebResponse errResp = webex.Response;
using (Stream respStream = errResp.GetResponseStream())
{
StreamReader reader = new StreamReader(respStream);
string text = reader.ReadToEnd();
}
}
catch (Exception e)
{ }
return null;
}
When there is an error, I catch it as WebException, and I read the Stream in order to know what the XML response is.
What I need to do, is post the XML data to the URL in Async.
So I changed the function:
public string uploadXMLData(string destinationUrl, string requestXml)
{
try
{
System.Uri uri = new System.Uri(destinationUrl);
using (WebClient client = new WebClient())
{
client.UploadStringCompleted
+= new UploadStringCompletedEventHandler(UploadStringCallback2);
client.UploadStringAsync(uri, requestXml);
}
}
catch (Exception e)
{ }
return null;
}
void UploadStringCallback2(object sender, UploadStringCompletedEventArgs e)
{
Console.WriteLine(e.Error);
}
How can I catch the WebException now and read the XML response?
Can I throw e.Error?
Any help would be appreciated
I found the solution:
void UploadStringCallback2(object sender, UploadStringCompletedEventArgs e)
{
if (e.Error != null)
{
object objException = e.Error.GetBaseException();
Type _type = typeof(WebException);
if (_type != null)
{
WebException objErr = (WebException)e.Error.GetBaseException();
WebResponse rsp = objErr.Response;
using (Stream respStream = rsp.GetResponseStream())
{
StreamReader reader = new StreamReader(respStream);
string text = reader.ReadToEnd();
}
throw objErr;
}
else
{
Exception objErr = (Exception)e.Error.GetBaseException();
throw objErr;
}
}
}

How to catch exception?

I am trying to call api and check its response, but when ever some wrong value is passed it stops the program. I want to add exception during request and response but not sure how to write in function.
This is how i call my REST call
public dynamic APICalls(JObject ljson, string endpoints, string method)
{
var httpReq = (HttpWebRequest)HttprequestObject(endpoints, method);
using (var streamWriter = new StreamWriter(httpReq.GetRequestStream()))
{
streamWriter.Write(ljson);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpReq.GetResponse();
var result = "";
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
//return "Success";
//not sure what to return
//here i have to add sql server code to enter into database
}
THis is code for request
public dynamic HttprequestObject(string endpoints, string method)
{
string url = Settings.API_TEST_VALUE + endpoints;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = method;
return httpWebRequest;
}
And right before request and right after response i want to catch exception.
At this point i have to catch exception
var httpResponse = (HttpWebResponse)httpReq.GetResponse();
If some one gives me hint how to catch that before it stops program.
There are 400, 401,402 errors, if something is wrong API sends json
For instance, while creating user :-- Email id already exists
But that points stops json and stops program..
Using try catch it will stop program, I want it to run and want to receive resposne.
Actually, API will send error .
For instance, status will be ;---401 UNAUTHORIZED
and resposnse will be
{ "reason": "Email already registered.", "success": false }
I am changed my code and
HttpWebResponse httpResponse;
try
{
//HttpWebResponse myHttpWebResponse = (HttpWebResponse)httpReq.GetResponse();
httpResponse = (HttpWebResponse)httpReq.GetResponse();
//myHttpWebResponse.Close();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
}
catch (WebException e)
{
Console.WriteLine("This program is expected to throw WebException on successful run." +
"\n\nException Message :" + e.Message);
if (e.Status == WebExceptionStatus.ProtocolError)
{
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return result;
//return "Success";
//not sure what to return
//here i have to add sql server code to enter into database
}
This is the new code, but I m not getting Json as return value, So i can show specific error.
For below Json what should I write?
{ "reason": "Email already registered.", "success": false }
please I m new to c# and if something is not clear please modify or ask question?
thank you
What you're looking for is called a try-catch statement:
try
{
var httpResponse = (HttpWebResponse)httpReq.GetResponse();
}
catch (WebException e)
{
// Here is where you handle the exception.
}
Using WebException as the type in the catch statement means only exceptions of that particular type will be caught.
In case an exception occurs, the e variable will contain exception details, such as a message passed from the method which three the exception and any inner exceptions encapsulated inside.
You can handle your web exceptions to get HttpStatusCode and Response Message this way:
public void SendAndGetResponseString()
{
try
{
// Here you call your API
}
catch (WebException e)
{
var result = GetResponceFromWebException(e);
if (result != null){
//
// Here you could use the HttpStatusCode and HttpResponseMessage
//
}
throw;
}
catch (Exception e)
{
// log exception or do nothing or throw it
}
}
private HttpRequestResponce GetResponceFromWebException(WebException e)
{
HttpRequestResponce result = null;
if (e.Status == WebExceptionStatus.ProtocolError)
{
try
{
using (var stream = e.Response.GetResponseStream())
{
if (stream != null)
{
using (var reader = new StreamReader(stream))
{
var responseString = reader.ReadToEnd();
var responce = ((HttpWebResponse) e.Response);
result = new HttpRequestResponce(responseString, responce.StatusCode);
}
}
}
}
catch (Exception ex)
{
// log exception or do nothing or throw it
}
}
return result;
}
public class HttpRequestResponce {
public HttpStatusCode HttpStatusCode { get;set; }
public string HttpResponseMessage {get;set;}
public HttpRequestResponce() { }
public HttpRequestResponce(string message, HttpStatusCode code)
{
HttpStatusCode=code;
HttpResponseMessage=message;
}
}
You encapsulate whatever method call or code block you want to prevent from throwing unhandled exceptions.
try
{
// code here
}
catch (Exception)
{
// here you may do whatever you want to do when an exception is caught
}
Ok,Finally I am able to Solve this.. Thanks everyone for you help.
This worked for me. I think I was not reading whole response.. So some how I think I realized and now its working ..
HttpWebResponse httpResponse;
try
{
httpResponse = (HttpWebResponse)httpReq.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
}
catch (WebException e)
{
Console.WriteLine("This program is expected to throw WebException on successful run." +
"\n\nException Message :" + e.Message);
if (e.Status == WebExceptionStatus.ProtocolError)
{
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
using (Stream data = e.Response.GetResponseStream())
using (var reader = new StreamReader(data))
{
string text = reader.ReadToEnd();
Console.WriteLine(text);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}

Categories

Resources