Add Custom Headers using HttpWebRequest - c#

I am not really sure what type of headers these highlighted values are, but how should I add them using HttpWebRequest?
Is the highlighted part considered body of the http request or header data? In other words, which way is correct?
Here is the code I am currently using:
HttpWebRequest request = (HttpWebRequest) WebRequest.Create("/securecontrol/reset/passwordreset");
request.Headers.Add("Authorization", "Basic asdadsasdas8586");
request.ContentType = "application/x-www-form-urlencoded";
request.Host = "www.xxxxxxxxxx.com";
request.Method = "POST";
request.Proxy = null;
request.Headers.Add("&command=requestnewpassword");
request.Headers.Add("&application=netconnect");
But should I use the following instead to build the Http Request above?
string reqString = "&command=requestnewpassword&application=netconnect";
byte[] requestData = Encoding.UTF8.GetBytes(reqString);
HttpWebRequest request = (HttpWebRequest) WebRequest.Create("/securecontrol/reset/passwordreset");
request.Headers.Add("Authorization", "Basic ashAHasd87asdHasdas");
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = requestData.Length;
request.Proxy = null;
request.Host = "www.xxxxxxxxxx.com";
request.Method = "POST";
using (Stream st = request.GetRequestStream())
st.Write(requestData, 0, requestData.Length);

A simple method of creating the service, adding headers and reading the JSON response,
private static void WebRequest()
{
const string WEBSERVICE_URL = "<<Web Service URL>>";
try
{
var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
if (webRequest != null)
{
webRequest.Method = "GET";
webRequest.Timeout = 20000;
webRequest.ContentType = "application/json";
webRequest.Headers.Add("Authorization", "Basic dcmGV25hZFzc3VudDM6cGzdCdvQ=");
using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
Console.WriteLine(String.Format("Response: {0}", jsonResponse));
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}

IMHO it is considered as malformed header data.
You actually want to send those name value pairs as the request content (this is the way POST works) and not as headers.
The second way is true.

Related

C# WebRequest - HTTP: 403 Forbidden ('_xsrf' argument missing from POST)

I'm stucked here at getting a WebResponse from HTTPWebRequest.
The WebRequest.GetResponse() Method throws a WebException
("500 Internal Server Error"). When i read the returned HTML it says:
HTTP 403: Forbidden ('_xsrf' argument missing from POST)
Anyone knows this Error or knows what Im doing wrong?
(Im trying to log in to a Website using POST)
EDIT:
My sourcecode:
private String GetLoginCookies(String pHTTPurl, String pUserIDwithFormID, String pPasswordWithFormID)
{
String loginPageUrl = pHTTPurl;
CookieContainer cookieContainer = new CookieContainer();
var Request = (HttpWebRequest)WebRequest.Create(loginPageUrl);
Request.CookieContainer = cookieContainer;
Request.Method = "GET";
WebResponse Response = Request.GetResponse();
HttpWebResponse HttpResponse = Response as HttpWebResponse;
CookieCollection cookies = null;
if (HttpResponse != null)
{
//Cookies die benötigt werden um den Loginvorgang abzuschließen
cookies = HttpResponse.Cookies;
}
string formParams = string.Format(pUserIDwithFormID + "&" + pPasswordWithFormID);
Request = (HttpWebRequest)WebRequest.Create(loginPageUrl);
Request.CookieContainer = cookieContainer;
Request.UserAgent = "I am not a Bot! Ok maybe..";
WebResponse resp = null;
Request.ContentType = "application/x-www-form-urlencoded";
Request.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
Request.ContentLength = bytes.Length;
using (Stream os = Request.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
try
{
resp = Request.GetResponse();
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
String TestResponse = sr.ReadToEnd();
}
}
catch (WebException WE)
{
DebugConsole.AppendText("HTTP Error:" + WE.Message + Environment.NewLine);
String HTML = new StreamReader(WE.Response.GetResponseStream()).ReadToEnd();
DebugConsole.AppendText(HTML);
return null;
}
String cookieHeader = resp.Headers["Set-cookie"];
if (String.IsNullOrEmpty(cookieHeader))
return null;
else
return cookieHeader;
}
This is actually because the web method requires anti csrf (cross site request forgery, more info here: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)) validation parameter. What you can do, is to append the csrf value to the request header:
postHeaders.Add("X-CSRFToken", CSRF);
Maybe you can paste your source code here if you need any help with that, so we can look after it
OK! Solution found!
After getting the response of the Log-In site, search in the "Set-cookie" Header for _xsrf. This is the Token you have to put in the header of the next POST request.

C# Ebay API Post-Order check_eligibility using HttpWebRequest

I'm trying to use the check_eligibility call from the eBay Post-Order API in C# very unsuccessfully. Every time I get a bad response. Here is one way I've tried:
string url = "https://api.ebay.com/post-order/v2/cancellation/check_eligibility";
HttpWebRequest cancelOrderRequest = (HttpWebRequest)WebRequest.Create(url);
cancelOrderRequest.Headers.Add("Authorization", "TOKEN " + AuthToken);
cancelOrderRequest.ContentType = "application/json";
cancelOrderRequest.Accept = "application/json";
cancelOrderRequest.Headers.Add("X-EBAY-C-MARKETPLACE-ID", "EBAY_US");
cancelOrderRequest.Headers.Add("legacyOrderId", ebayFullOrderId);
cancelOrderRequest.Method = "POST";
HttpWebResponse response = (HttpWebResponse)cancelOrderRequest.GetResponse();
And here is another way I've tried:
string url = "https://api.ebay.com/post-order/v2/cancellation/check_eligibility";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Authorization", "TOKEN " + AuthToken);
httpWebRequest.Headers.Add("X-EBAY-C-MARKETPLACE-ID", "EBAY_US");
httpWebRequest.Accept = "application/json";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"legacyOrderId\":\"###-###\"";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
Regardless of which way I try both came back with the same message, "The remote server returned an error: (400) Bad Request." If anyone could point me in the right direction I'd greatly appreciate it. Thanks.
My second code example ended up being the correct way to solve my problem. What I realized was my json was slightly off. I was missing the extra } at the end. The below updated json syntax fixed my problem going with the code from my second example.
var json = "{\"legacyOrderId\":\"" + ebayFullOrderId + "\"}";
Please try this code:
private void MakeRequests()
{
HttpWebResponse response;
if (RequestEbay(out response))
{
response.Close();
}
}
private bool RequestEbay(out HttpWebResponse response)
{
response = null;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.ebay.com/ws/api.dll");
request.Headers.Add("X-EBAY-API-SITEID", #"0");
request.Headers.Add("X-EBAY-API-COMPATIBILITY-LEVEL", #"967");
request.Headers.Add("X-EBAY-API-CALL-NAME", #"GetOrders");
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;
string body = #"<?xml version=""1.0"" encoding=""utf-8""?>
<GetOrdersRequest xmlns=""urn:ebay:apis:eBLBaseComponents"">
<RequesterCredentials>
<eBayAuthToken>!!!!!!!!!!!!!!!!YOUR EBAY TOKEN!!!!!!!!!!!!!!!!1</eBayAuthToken>
</RequesterCredentials>
<ErrorLanguage>en_US</ErrorLanguage>
<WarningLevel>High</WarningLevel>
<CreateTimeFrom>2016-12-01T19:09:02.768Z</CreateTimeFrom>
<CreateTimeTo>2017-12-15T19:09:02.768Z</CreateTimeTo>
<OrderRole>Seller</OrderRole>
</GetOrdersRequest>";
byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(body);
request.ContentLength = postBytes.Length;
Stream stream = request.GetRequestStream();
stream.Write(postBytes, 0, postBytes.Length);
stream.Close();
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError) response = (HttpWebResponse)e.Response;
else return false;
}
catch (Exception)
{
if(response != null) response.Close();
return false;
}
return true;
}

How can I Post data using HttpWebRequest?

I have this HttpWebRequest:
var request = HttpWebRequest.Create("http://example.com/api/Phrase/GetJDTO");
request.ContentType = "application/json";
request.Method = "POST";
But I need to add a payload to the body of the request like this:
Jlpt = 2
Can someone help and tell me how I can add data to the POST ?
You can do by this
var request = HttpWebRequest.Create("http://example.com/api/Phrase/GetJDTO");
var postData = "Jlpt = 2";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
but I suggest you use HttpClient rather than HttpWebRequest in this case
if (data != null)
{
request.ContentType = "application/json";
using (var stream = new StreamWriter(request.GetRequestStream()))
{
var serialized = JsonConvert.SerializeObject(data);
stream.Write(serialized);
}
}
else
{
request.ContentLength = 0;
}
where data is any object you want to send

How to use WebRequest in c#

I'am trying to use example api call in below link please check link
http://sendloop.com/help/article/api-001/getting-started
My account is "code5" so i tried 2 codes to get systemDate.
1. Code
var request = WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
request.ContentType = "application/json; charset=utf-8";
string text;
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
2.Code
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";
But i don't know that i use correctly api by above codes ?
When i use above codes i don't see any data or anything.
How can i get and post api to Sendloop.And how can i use api by using WebRequest ?
I will use api first time in .net so
any help will be appreciated.
Thanks.
It looks like you need to post your API key to the endpoint when making requests. Otherwise, you will not be authenticated and it will return an empty response.
To send a POST request, you will need to do something like this:
var request = WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
request.ContentType = "application/json; charset=utf-8";
string postData = "APIKey=xxxx-xxxxx-xxxxx-xxxxx-xxxxx";
request.Method = "POST";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
request.ContentLength = data.Length;
Stream newStream = request.GetRequestStream(); //open connection
newStream.Write(data, 0, data.Length); // Send the data.
newStream.Close();
string text;
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
string userAuthenticationURI =
"https://maps.googleapis.com/maps/api/distancematrix/json?origins="+ originZip +
"&destinations="+ DestinationZip + "&units=imperial&language=en-
EN&sensor=false&key=Your API Key";
if (!string.IsNullOrEmpty(userAuthenticationURI))
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(userAuthenticationURI);
request.Method = "GET";
request.ContentType = "application/json";
WebResponse response = request.GetResponse();
var responseString = new
StreamReader(response.GetResponseStream()).ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject(responseString);
}

Sequence of HttpWebRequest

I am currently in the process of automating a web interface for administrating users of an FTP.
I am trying to do this with HttpWebRequest, i have one call that logs me on the site and the second call is supose to add a new user for the FTP access.
I have tried my two urls in the browser and they work, they end up creating a user.
string login = "https://www.ftpsite.net/./panel/index.php?txvUsername=myaccount&txvPassword=myPassword&submitButton=Login";
this gets me logged in when i enter it in the browser address bar.
the second call to create a user is as follows.
string createUser = "https://www.ftpSite.net/panel/ftpsites/updatelogin?login_id=&login=toto123&realname=realnametoto&homedir=root&passwd=superpassword11&expdate=01-01-2100&neverExpire=on&quota_value=0&quota_unit=GB&group_id=0&status=on&ftp=on&filelist=on&ftp_download=on&http=on&web_filelist=on&web_download=on&email=";
This creates a user when i enter it in the browser's address bar if it follows the one that logs us in.
My problem is that i am trying to do this using HttpWebRequest and without success. I can get myself logged in but when i try to create the user it seems to return a "bad" error code saying i have created too many users already which isnt the case since i can create more after that call. Here is the code i use with HtttpRequest
_datCookie = new CookieContainer();
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(login);
httpWebRequest.Method = "POST";
httpWebRequest.CookieContainer = _datCookie;
WebResponse response = httpWebRequest.GetResponse();
referer = response.ResponseUri.AbsoluteUri;
Stream requestStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(requestStream);
_datCookie = httpWebRequest.CookieContainer;
response.Close();
httpWebRequest = (HttpWebRequest)WebRequest.Create(createUser);
httpWebRequest.CookieContainer = _datCookie;
httpWebRequest.Referer = referer;
httpWebRequest.Method = "POST";
response = httpWebRequest.GetResponse();
requestStream = response.GetResponseStream();
streamReader = new StreamReader(requestStream);
webBrowser.DocumentText = streamReader.ReadToEnd();
response.Close();
What i caught and tried to imitate without success here.
Are you sure they should be POST requests? The URLs seem to have all of the fields in the query-string, which suggests they should be GET requests instead.
Based on the Fiddler screen-shot, you need to make a POST request with the fields in the body, not the query-string:
var cookies = new CookieContainer();
// Request 1 : Login
var request = (HttpWebRequest)WebRequest.Create("https://www.ftpsite.net/./panel/index.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = cookies;
string postData = "txvUsername=myaccount&txvPassword=myPassword&submitButton=Login";
byte[] postBytes = Encoding.Default.GetBytes(postData);
request.ContentLength = postBytes.Length;
using (Stream bod = request.GetRequestStream())
{
body.Write(postBytes, 0, postBytes.Length);
}
WebResponse response = request.GetResponse();
string referer = response.ResponseUri.AbsoluteUri;
// Request 2 : Create user
request = (HttpWebRequest)WebRequest.Create("https://www.ftpSite.net/panel/ftpsites/updatelogin");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = cookies;
postData = "login_id=&login=toto123&realname=realnametoto&homedir=root&passwd=superpassword11&expdate=01-01-2100&neverExpire=on&quota_value=0&quota_unit=GB&group_id=0&status=on&ftp=on&filelist=on&ftp_download=on&http=on&web_filelist=on&web_download=on&email=";
postBytes = Encoding.Default.GetBytes(postData);
request.ContentLength = postBytes.Length;
using (Stream bod = request.GetRequestStream())
{
body.Write(postBytes, 0, postBytes.Length);
}
response = request.GetResponse();
requestStream = response.GetResponseStream();
streamReader = new StreamReader(requestStream);
webBrowser.DocumentText = streamReader.ReadToEnd();
response.Close();

Categories