C# HttpWebRequest.GetResponse encoding URL - c#

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
}
}
}

Related

Cannot send a content-body with this verb-type using streamWriter & json

I am testing sending some data to an api. The demo code on their site is copied below (the address and data I have changed as its a clients data).
On the line, using (var streamWritier...) I get the error below,
Cannot send a content-body with this verb-type
I have not seen data sent this way before. Is there something I am missing?
using System;
using System.IO;
using System.Net;
namespace Test
{
class Program
{
static void Main(string[] args)
{
var authStr = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(#"username:password"));
var httpRequest = (HttpWebRequest)HttpWebRequest.Create("https://some-api");
httpRequest.Headers.Add("Authorization", "Basic " + authStr);
WebResponse response = null;
try
{
httpRequest.ContentType = "application/json";
httpRequest.Accept = "application/json";
string data = "{ \"RequestType\": \"ClientAdhoc\", \"IdentifierType\": \"KDF\", \"ReqDate\": 20190101"}";
using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
{ streamWriter.Write(data); streamWriter.Flush(); streamWriter.Close(); }
response = httpRequest.GetResponse();
var responseStream = response.GetResponseStream();
var reader = new StreamReader(responseStream);
Console.WriteLine("Response received: [{0}].", reader.ReadToEnd());
}
catch (Exception exception)
{
Console.WriteLine("Exception occurred: [{0}].", exception.Message);
Console.WriteLine(exception.StackTrace);
}
}
}
}

Paypal saved card rest API through 400 Bad Request error in C#

I am developing application using .net MVC C#. I tried to call rest API of PayPal for save credit card details, my code were working fine but suddenly it starting through 400 Bad Request exception. here is my code,
private static async Task<string> StorePaymentCards(string accessToken, PaymentInfoModel cardDetails)
{
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.sandbox.paypal.com/v1/vault/credit-card");
var result = "";
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
httpWebRequest.Accept = "application/json; charset=utf-8";
httpWebRequest.Headers.Add("Authorization", "Bearer " + accessToken);
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
var loginjson = new JavaScriptSerializer().Serialize(new
{
payer_id = cardDetails.PayerId.Trim(),
type = cardDetails.CardType.Trim(),
number = cardDetails.CardNumber.Trim(),
expire_month = cardDetails.ExpireMonth.Trim(),
expire_year = cardDetails.ExpireYear.Trim(),
first_name = cardDetails.FirstName.Trim()
});
streamWriter.Write(loginjson);
streamWriter.Flush();
streamWriter.Close();
//The code fails when creating the Response here, and go into catch block
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
}
catch (Exception ex)
{
return ex.GetBaseException().Message;
}
}
}
Can anyone help me out from this error?
Thank you in advance.
private static async Task<string> StorePaymentCards(string accessToken, PaymentInfoModel cardDetails)
{
try
{
//my stuff
}
catch (WebException ex)
{
string text = null;
using (WebResponse response = ex.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
using (var reader = new StreamReader(data))
{
text = reader.ReadToEnd();
Console.WriteLine(text);
}
}
return text; //ex.GetBaseException().Message;
}
}
This is changed I have done in my catch block to trace proper error, so it return me that error which I was facing.

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
}

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);
}

Returning value from a method

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.

Categories

Resources