programatically send a form with POST - c#

I need to programatically send a form over POST. I have 4 fields, one checkbox and a submit button. how can i go about it?

I use these functions assuming your question is about a forms application.
You can call
HttpPost(
post_url,
"field_name_1", value_1,
"field_name_2", value_2,
...);
Here they are:
public static string HttpPost(string url, params object[] postData)
{
StringBuilder post = new StringBuilder();
for (int i = 0; i < postData.Length; i += 2)
post.Append(string.Format("{0}{1}={2}", i == 0 ? "" : "&", postData[i], postData[i + 1]));
return HttpPost(url, post.ToString());
}
public static string HttpPost(string url, string postData)
{
postData = postData.Replace("\r\n", "");
try
{
WebRequest req = WebRequest.Create(url);
byte[] send = Encoding.Default.GetBytes(postData);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = send.Length;
Stream sout = req.GetRequestStream();
sout.Write(send, 0, send.Length);
sout.Flush();
sout.Close();
WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string returnvalue = sr.ReadToEnd();
return returnvalue;
}
catch (Exception ex)
{
Debug.WriteLine("POST Error on {0}\n {1}", url, ex.Message);
return "";
}
}

This should do the trick:
NameValueCollection formData = new NameValueCollection();
formData.Add("field1", "value1");
formData.Add("field2", "value2");
// ... and so on ...
WebClient client = new WebClient();
byte[] result = client.UploadValues("http://www.example.com", formData);
The information, that you have checkboxes or submit buttons is not transferred. It's always name and value.

JQuery $.Post() does exactly that.

Related

How do I use C# to post to this form grammatically?

I am trying to check my gift card balance, (I have many) on the following website and I want to automate via a C# program.
https://www.fivebackgift.com/
It is form1 in the source code im interested in. This is my code:
class Program
{
public static string HttpPost(string url, params object[] postData)
{
StringBuilder post = new StringBuilder();
for (int i = 0; i < postData.Length; i += 2)
post.Append(string.Format("{0}{1}={2}", i == 0 ? "" : "&", postData[i], postData[i + 1]));
return HttpPost(url, post.ToString());
}
public static string HttpPost(string url, string postData)
{
postData = postData.Replace("\r\n", "");
try
{
WebRequest req = WebRequest.Create(url);
byte[] send = Encoding.Default.GetBytes(postData);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = send.Length;
Stream sout = req.GetRequestStream();
sout.Write(send, 0, send.Length);
sout.Flush();
sout.Close();
WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string returnvalue = sr.ReadToEnd();
return returnvalue;
}
catch (Exception ex)
{
Debug.WriteLine("POST Error on {0}\n {1}", url, ex.Message);
return "";
}
}
static void Main(string[] args)
{
HttpPost("https://www.fivebackgift.com/Card/_Login?returnUrl=Transactions",
"CardNumber", "CREDIT NUMBER",
"ExpirationMonth", "MONTH",
"ExpirationYear", "YEAR",
"SecurityCode", "CODE");
}
}
I just want to see if the website would give me a response. The following error is what I get:
POST Error on https://www.fivebackgift.com/Card/_Login?returnUrl=Transactions
The remote server returned an error: (404) Not Found.
How do I figure out what the real URL should be?

How to create Journal entry in QuickBooks Online

I am trying to use C# to create a Journal entry in Quickbooks Online V3 API.
Things I have done:
Check JSON Values and format
Checked Header and accept.
Header info:
Accept : application/json
Authorization : OAuth oauth_token="************",oauth_nonce="cfc36792-8f9a-4202-9fec-be0a610eed8e",oauth_consumer_key="************",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1435189421",oauth_version="1.0",oauth_signature="***"
Content-Length : 642
Content-Type : application/json
Host : qb.sbfinance.intuit.com
//till here everything is fine not sure about last two lines..
//not sure should i add this to my header or not..
X-NewRelic-ID : UQMAU15RGwcAUllSDwc=
X-NewRelic-Transaction : PxQAVVRUCgMIUiRXdHMBICETGlUDChAHHEAPVgoPBgILU3xUciMFJCEUG0MDUwFVAV1WVBVs
My code:
public static void Main()
{
// JournalEndPoint lnew = new JournalEndPoint();
// string Json=lnew.CreateJournal();
string consumerKey = "***";
string consec = "***";
string appkeysec1 = "***";
string appkey1 = "***";
string returnvalue = ExecuteV3Query(consumerKey, consec, appkey1, appkeysec1, "1397754725", "select * from employee where active=TRUE");
}
public static string ExecuteV3Query(string consumerKey, string consumerSecret, string accessToken, string accessTokenSecret, string CompanyId, string query)
{
string encodedQuery = RestSharp.Contrib.HttpUtility.UrlEncode(query);
string uri = string.Format("https://quickbooks.api.intuit.com/v3/company/{0}/journalentry", CompanyId, encodedQuery);
HttpWebRequest httpWebRequest = WebRequest.Create(uri) as HttpWebRequest;
httpWebRequest.Method = "POST";
string JSonvalue = CreateUserJson();
httpWebRequest.ContentType = "application/json";
httpWebRequest.Accept = "application/json";
httpWebRequest.Headers.Add("Authorization", GetDevDefinedOAuthHeader(consumerKey, consumerSecret, accessToken, accessTokenSecret, httpWebRequest, null));
//HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
/*
* using (Stream data = httpWebResponse.GetResponseStream())
{
//return XML response
return new StreamReader(data).ReadToEnd();
}
*/
var result = "";
HttpWebResponse httpResponse;
try
{
httpResponse = (HttpWebResponse)httpWebRequest.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;
}
GetDevDefineHeader() will create header and return type is string.
In your url, I do not see the use of encoded query and why are you passing it?
Please check the docs for correct endpoints for CRUD and query operations-
https://developer.intuit.com/docs/api/accounting/JournalEntry
See this example for GET using dev defined-
https://gist.github.com/IntuitDeveloperRelations/0913b4c224de758fde0a
Similarly there is a post example here, you can write similarly for JE-
//string res = CreateV3Customer(consumerKey, consumerSecret, accessToken, accessTokenSecret, realmId);
public string CreateV3Customer(string consumerKey, string consumerSecret, string accessToken, string accessTokenSecret, string realmId)
{
StringBuilder request = new StringBuilder();
StringBuilder response = new StringBuilder();
var requestBody = "{\"FamilyName\":\"Jack\"}";
HttpWebRequest httpWebRequest = WebRequest.Create("https://quickbooks.api.intuit.com/v3/company/"+realmId+"/customer") as HttpWebRequest;
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("Authorization", GetDevDefinedOAuthHeader(consumerKey, consumerSecret, accessToken,accessTokenSecret,httpWebRequest, requestBody));
request.Append(requestBody);
UTF8Encoding encoding = new UTF8Encoding();
byte[] content = encoding.GetBytes(request.ToString());
using (var stream = httpWebRequest.GetRequestStream())
{
stream.Write(content, 0, content.Length);
}
HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
using (Stream data = httpWebResponse.GetResponseStream())
{
string customerr = new StreamReader(data).ReadToEnd();
return customerr;
}
}

Post form data using HttpWebRequest

I want to post some form data to a specified URL that isn't inside my own web application. It has the same domain, such like "domain.client.nl". The web application has a url "web.domain.client.nl" en the url where I want to post to is "idp.domain.client.nl".
But my code does nothing..... does someone knows what I'm doing wrong?
Wouter
StringBuilder postData = new StringBuilder();
postData.Append(HttpUtility.UrlEncode(String.Format("username={0}&", uname)));
postData.Append(HttpUtility.UrlEncode(String.Format("password={0}&", pword)));
postData.Append(HttpUtility.UrlEncode(String.Format("url_success={0}&", urlSuccess)));
postData.Append(HttpUtility.UrlEncode(String.Format("url_failed={0}", urlFailed)));
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] postBytes = ascii.GetBytes(postData.ToString());
// set up request object
HttpWebRequest request;
try
{
request = (HttpWebRequest)HttpWebRequest.Create(WebSiteConstants.UrlIdp);
}
catch (UriFormatException)
{
request = null;
}
if (request == null)
throw new ApplicationException("Invalid URL: " + WebSiteConstants.UrlIdp);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
// add post data to request
Stream postStream = request.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Flush();
postStream.Close();
Both the field name and the value should be url encoded.
format of the post data and query string are the same
The .net way of doing is something like this
NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(String.Empty);
outgoingQueryString.Add("field1","value1");
outgoingQueryString.Add("field2", "value2");
string postdata = outgoingQueryString.ToString();
This will take care of encoding the fields and the value names
Try this:
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var postData = "thing1=hello";
postData += "&thing2=world";
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();
You are encoding the form incorrectly. You should only encode the values:
StringBuilder postData = new StringBuilder();
postData.Append("username=" + HttpUtility.UrlEncode(uname) + "&");
postData.Append("password=" + HttpUtility.UrlEncode(pword) + "&");
postData.Append("url_success=" + HttpUtility.UrlEncode(urlSuccess) + "&");
postData.Append("url_failed=" + HttpUtility.UrlEncode(urlFailed));
edit
I was incorrect. According to RFC1866 section 8.2.1 both names and values should be encoded.
But for the given example, the names do not have any characters that needs to be encoded, so in this case my code example is correct ;)
The code in the question is still incorrect as it would encode the equal sign which is the reason to why the web server cannot decode it.
A more proper way would have been:
StringBuilder postData = new StringBuilder();
postData.AppendUrlEncoded("username", uname);
postData.AppendUrlEncoded("password", pword);
postData.AppendUrlEncoded("url_success", urlSuccess);
postData.AppendUrlEncoded("url_failed", urlFailed);
//in an extension class
public static void AppendUrlEncoded(this StringBuilder sb, string name, string value)
{
if (sb.Length != 0)
sb.Append("&");
sb.Append(HttpUtility.UrlEncode(name));
sb.Append("=");
sb.Append(HttpUtility.UrlEncode(value));
}
Use this code:
internal void SomeFunction() {
Dictionary<string, string> formField = new Dictionary<string, string>();
formField.Add("Name", "Henry");
formField.Add("Age", "21");
string body = GetBodyStringFromDictionary(formField);
// output : Name=Henry&Age=21
}
internal string GetBodyStringFromDictionary(Dictionary<string, string> formField)
{
string body = string.Empty;
foreach (var pair in formField)
{
body += $"{pair.Key}={pair.Value}&";
}
// delete last "&"
body = body.Substring(0, body.Length - 1);
return body;
}
List<KeyValuePair<string, string>> formField= new List<KeyValuePair<string,string>>();
formField.Add(new KeyValuePair<string, string>("Name", "Henry"));
formField.Add(new KeyValuePair<string, string>("Age", "21"));
var body = string.Join("&", formField.Select(kvp => $"{kvp.Key}={kvp.Value}"));

Google Api get token request returns invalid_request

I'm trying to get Google APi's access_token using c# and always getting error message invalid_request. There is my code:
var Params = new Dictionary<string, string>();
Params["client_id"] = GoogleApplicationAPI.CLIENT_ID;
Params["client_secret"] = GoogleApplicationAPI.CLIENT_SECRET;
Params["code"] = "4/08Z_Us0a_blkMlXihlixR1579TYu.smV5ucbI8U4VOl05ti8ZT3ZD4CgMcgI";
Params["redirect_uri"] = GoogleApplicationAPI.RETURN_URL;
Params["grant_type"] = "authorization_code";
var RequestData = "";
foreach (var Item in Params)
{
RequestData += Item.Key + "=" + HttpUtility.UrlEncode(Item.Value) + "&";
}
string Url = "https://accounts.google.com/o/oauth2/token";
var request = (HttpWebRequest) WebRequest.Create(Url);
request.Method = HttpMethod.Post.ToString();
request.ContentType = "application/x-www-form-urlencoded";
var SendData = Encoding.UTF8.GetBytes(RequestData);
try
{
request.ContentLength = SendData.Length;
Stream OutputStream = request.GetRequestStream();
OutputStream.Write(SendData, 0, SendData.Length);
} catch {}
try
{
using (var response = (HttpWebResponse) request.GetResponse())
{
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
string JSON = sr.ReadToEnd();
}
} catch {}
I use https://developers.google.com/accounts/docs/OAuth2WebServer#offline
Try removing the call to HttpUtility.UrlEncode on each item in the request data. You shouldn't need to do this as the data is not going into the url it's being POSTed. This is no doubt diluting the information being sent which is resulting in your Invalid Request response.

Remote HTTP Post with C# [duplicate]

This question already has answers here:
Send HTTP POST request in .NET
(16 answers)
Closed 9 years ago.
How do you do a Remote HTTP Post (request) in C#?
This is code from a small app I wrote once to post a form with values to a URL. It should be pretty robust.
_formValues is a Dictionary<string,string> containing the variables to post and their values.
// encode form data
StringBuilder postString = new StringBuilder();
bool first=true;
foreach (KeyValuePair pair in _formValues)
{
if(first)
first=false;
else
postString.Append("&");
postString.AppendFormat("{0}={1}", pair.Key, System.Web.HttpUtility.UrlEncode(pair.Value));
}
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] postBytes = ascii.GetBytes(postString.ToString());
// set up request object
HttpWebRequest request;
try
{
request = WebRequest.Create(url) as HttpWebRequest;
}
catch (UriFormatException)
{
request = null;
}
if (request == null)
throw new ApplicationException("Invalid URL: " + url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
// add post data to request
Stream postStream = request.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Close();
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
I use this very simple class:
public class RemotePost{
private System.Collections.Specialized.NameValueCollection Inputs
= new System.Collections.Specialized.NameValueCollection() ;
public string Url = "" ;
public string Method = "post" ;
public string FormName = "form1" ;
public void Add( string name, string value ){
Inputs.Add(name, value ) ;
}
public void Post(){
System.Web.HttpContext.Current.Response.Clear() ;
System.Web.HttpContext.Current.Response.Write( "<html><head>" ) ;
System.Web.HttpContext.Current.Response.Write( string .Format( "</head><body onload=\"document.{0}.submit()\">" ,FormName)) ;
System.Web.HttpContext.Current.Response.Write( string .Format( "<form name=\"{0}\" method=\"{1}\" action=\"{2}\" >" ,
FormName,Method,Url)) ;
for ( int i = 0 ; i< Inputs.Keys.Count ; i++){
System.Web.HttpContext.Current.Response.Write( string .Format( "<input name=\"{0}\" type=\"hidden\" value=\"{1}\">" ,Inputs.Keys[i],Inputs[Inputs.Keys[i]])) ;
}
System.Web.HttpContext.Current.Response.Write( "</form>" ) ;
System.Web.HttpContext.Current.Response.Write( "</body></html>" ) ;
System.Web.HttpContext.Current.Response.End() ;
}
}
And you use it thusly:
RemotePost myremotepost = new RemotePost() ;
myremotepost.Url = "http://www.jigar.net/demo/HttpRequestDemoServer.aspx" ;
myremotepost.Add( "field1" , "Huckleberry" ) ;
myremotepost.Add( "field2" , "Finn" ) ;
myremotepost.Post() ;
Very clean, easy to use and encapsulates all the muck. I prefer this to using the HttpWebRequest and so forth directly.
You can use WCF or create a WebRequest
var httpRequest = (HttpWebRequest)WebRequest.Create("http://localhost/service.svc");
var httpRequest.Method = "POST";
using (var outputStream = httpRequest.GetRequestStream())
{
// some complicated logic to create the message
}
var response = httpRequest.GetResponse();
using (var stream = response.GetResponseStream())
{
// some complicated logic to handle the response message.
}
Also System.Net.WebClient
Use the WebRequest.Create() and set the Method property.
Im using the following piece of code for calling webservices using the httpwebrequest class:
internal static string CallWebServiceDetail(string url, string soapbody,
int timeout) {
return CallWebServiceDetail(url, soapbody, null, null, null, null,
null, timeout);
}
internal static string CallWebServiceDetail(string url, string soapbody,
string proxy, string contenttype, string method, string action,
string accept, int timeoutMilisecs) {
var req = (HttpWebRequest) WebRequest.Create(url);
if (action != null) {
req.Headers.Add("SOAPAction", action);
}
req.ContentType = contenttype ?? "text/xml;charset=\"utf-8\"";
req.Accept = accept ?? "text/xml";
req.Method = method ?? "POST";
req.Timeout = timeoutMilisecs;
if (proxy != null) {
req.Proxy = new WebProxy(proxy, true);
}
using(var stm = req.GetRequestStream()) {
XmlDocument doc = new XmlDocument();
doc.LoadXml(soapbody);
doc.Save(stm);
}
using(var resp = req.GetResponse()) {
using(var responseStream = resp.GetResponseStream()) {
using(var reader = new StreamReader(responseStream)) {
return reader.ReadToEnd();
}
}
}
}
This can be easily used to call a webservice
public void TestWebCall() {
const string url =
"http://www.ecubicle.net/whois_service.asmx/HelloWorld";
const string soap =
#"<soap:Envelope xmlns:soap='about:envelope'>
<soap:Body><HelloWorld /></soap:Body>
</soap:Envelope>";
string responseDoc = CallWebServiceDetail(url, soap, 1000);
XmlDocument doc = new XmlDocument();
doc.LoadXml(responseDoc);
string response = doc.DocumentElement.InnerText;
}
HttpWebRequest HttpWReq =
(HttpWebRequest)WebRequest.Create("http://www.google.com");
HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
Console.WriteLine(HttpWResp.StatusCode);
HttpWResp.Close();
Should print "OK" (200) if the request was successful
The problem when beginning with high-level language like C#, Java or PHP is that people may have never known how simple the underground is in reality. So here’s a short introduction:
http://reboltutorial.com/blog/raw-http-request/

Categories

Resources