I basically have some idea how to use HttpWebRequests but I am pretty newbie. So I want to submit the following token with the Post method.
authenticity_token=pkhn7pwt3QATOpOAfBERZ%2BRIJ7oBEqGFpnF0Ir4RtJg%3D&question%5Bquestion_text%5D=TEST+TEST+TEST&authenticity_token=pkhn7pwt3QATOpOAfBERZ%2BRIJ7oBEqGFpnF0Ir4RtJg%3D
What it does is click a button and send the text "TEST TEST TEST", this is the token I am getting from firebug when I click the button I want to.
To send some data with a Http Post Request you can try using the following code:
check 'var serverResponse' for server response.
string targetUrl = "http://www.url.url";
var postBytes = Encoding.Default.GetBytes(#"authenticity_token=pkhn7pwt3QATOpOAfBERZ%2BRIJ7oBEqGFpnF0Ir4RtJg%3D&question%5Bquestion_text%5D=TEST+TEST+TEST&authenticity_token=pkhn7pwt3QATOpOAfBERZ%2BRIJ7oBEqGFpnF0Ir4RtJg%3D");
var httpRequest = (HttpWebRequest)WebRequest.Create(targetUrl);
httpRequest.ContentLength = postBytes.Length;
httpRequest.Method = "POST";
using (var requestStream = httpRequest.GetRequestStream())
requestStream.Write(postBytes, 0, postBytes.Length);
var httpResponse = httpRequest.GetResponse();
using (var responseStream = httpResponse.GetResponseStream())
if (responseStream != null)
using (var responseStreamReader = new StreamReader(responseStream))
{
var serverResponse = responseStreamReader.ReadToEnd();
}
Yet another solution:
// you can get the correct encoding from your site's response headers
Encoding encoding = Encoding.UTF8;
string targetUrl = "http://example.com";
var request = (HttpWebRequest)WebRequest.Create(targetUrl);
var formData = new Dictionary<string, object>();
formData["authenticity_token"] = "pkhn7pwt3QATOpOAfBERZ+RIJ7oBEqGFpnF0Ir4RtJg=";
formData["question[question_text]"] = "TEST TEST TEST";
bool isFirstField = true;
StringBuilder query = new StringBuilder();
foreach (KeyValuePair<string, object> field in formData)
{
if (!isFirstField)
query.Append("&");
else
isFirstField= false;
query.AppendFormat("{0}={1}", field.Key, field.Value);
}
string urlEncodedQuery = Uri.EscapeDataString(query.ToString());
byte[] postData = encoding.GetBytes(urlEncodedQuery);
request.ContentLength = postData.Length;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (BinaryWriter bw = new BinaryWriter(request.GetRequestStream()))
bw.Write(postData);
var response = request.GetResponse() as HttpWebResponse;
// TODO: process response
Related
I am trying to get cognos report using siteminder token, below is my code.
string cognosUrl = "https://cognos.blah.com";
string reportPath = "/c10/cgi-bin/cognosisapi.dll/rds/reportData/report/"; string reportId = "ildjfsldkf"; //prod
cognosUrl += string.Concat(reportPath, reportId,"?blahblah");
string targetUrl = cognosUrl;
string strFormvalues = string.Concat("TARGET=",targetUrl);
ASCIIEncoding encoder = new ASCIIEncoding();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUrl);
byte[] data = encoder.GetBytes(strFormvalues);
request.AllowAutoRedirect = false;
request.Timeout = 120000;
request.ContentLength = data.Length;
request.ContentType = "text/xml;charset=\"utf-8\"";
request.Method = "POST";
request.Headers.Add(HttpRequestHeader.Cookie,"SMSESSION="+stoken);
request.GetRequestStream().Write(data, 0, data.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string json = reader.ReadToEnd();
byte[] byteArray = Encoding.UTF8.GetBytes(json);
MemoryStream restream = new MemoryStream(byteArray);
using (Stream output = File.OpenWrite(#"c:\\Projects\\Test_"+DateTime.Now.ToString("yyyyMMddHHmmssfff")+".txt"))
using (Stream input = restream)
{
if (input != null) input.CopyTo(output);
}
// var results = serializer.DeserializeObject(json);
reader.Close();
dataStream.Close();
response.Close();
But I am getting response as " DPR-ERR-2101 Your request was invalid.Please contact your administrator."
I am not using C# myself, but a few recommendations while debugging this:
If you are only posting a URL, why not use GET instead of POST?
Try paste the targetURL in your browser, see what happens.
In my setup, when I paste the URL in the browser, I am always redirected before I receive an answer. (to a URL like, /cgi-bin/cognosisapi.dll/rds/sessionOutput/conversationID/i292ED29A62474697AD44306A388F5BBB You are preventing that to happen, that might be an issue)
Hope that helps.
I want to send message on facebook. This is my method to make a post request:
public static string http_post(string url, string data)
{
var cookiespost = new CookieContainer();
ServicePointManager.Expect100Continue = false;
var request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = cookiespost;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (var requestStream = request.GetRequestStream())
using (var writer = new StreamWriter(requestStream))
{
writer.Write(data);
}
using (var responseStream = request.GetResponse().GetResponseStream())
using (var reader = new StreamReader(responseStream))
{
var result = reader.ReadToEnd();
cookies = cookiespost;
return result;
}
}
data:
"fb_dtsg=AQHcmRlBsZsj&charset_test=%E2%82%AC%2C%C2%B4%2
C%E2%82%AC%2C%C2%B4%2C%E6%B0%B4%2C%D0%94%2C%D0%84&ids%
5B100002079663653%5D=100002079663653&text_ids%
5B100002079663653%5D=%D0%9D%D0%B8%D0%BA%D0%B8%D1%
82%D0%B0+%D0%A5%D0%B8%D0%B6%D0%BD%D1%8F%D0%BA&body="
+ textofmessage + "&Send=%D0%9D%D0%B0%D0%B4%
D1%96%D1%81%D0%BB%D0%B0%D1%82%D0%B8";
url:
https://m.facebook.com/messages/send/?icm=1
But the message is not sent in the text of the response I get login page.
How is it possible to perform sending a message ?
Thanks!
I want to do a create via a webservice which needs a uri like this:
http://<url>/webservice.php?operation=<operation>&elementType=<elementType>&element=<element>&
my problem is, element is all information of an email with html body, which is about 6000 characters.
I want to call the url like this:
var request = WebRequest.Create(urlToUse.ToString());
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = urlToUse.Length;
var requestStream = request.GetRequestStream();
var requestStreamWriter = new StreamWriter(requestStream);
requestStreamWriter.Write(urlToUse);
requestStreamWriter.Close();
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
if (responseStream == null) return null;
var responseStreamReader = new StreamReader(responseStream);
var responseFromServer = responseStreamReader.ReadToEnd();
responseStreamReader.Close();
responseStream.Close();
response.Close();
but it breaks at
var response = request.GetResponse();
and says the uri is too long.
I can't change the server's max length of the url and the webservice needs the parameters in the url.
I haven't found a suitable solution for me yet so any help is appreciated.Update:
For anyone facing the same issue, the solution that worked for me was to put my query into an byte-Array like
var encoding = new UTF8Encoding();
byte[] bytes = enconding.GetBytes((queryString));
and writing that into the webrequest instead of my queryString
var stream = request.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
You can put data in the body of the request with something a little like this:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://<url>/webservice.php");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var jsonContent = JsonConvert.SerializeObject(new YourObject
{
// Pseudo code... Replace <...> with your values etc
Operation = <YourOperation>,
ElementType = <YourElementType>,
Element = <YourElement>,
// etc...
});
HttpResponseMessage response;
using (HttpContent httpContent = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
{
response = await client.PostAsync("youroperation/", httpContent);
}
// Do something with response if you want
}
This is JSON based but could be anything you want to pass... This is a simple example that will hopefully give you an idea of how you can proceed.
You need to split the urlToUse at the question mark:
Something like this (not tested)
string[] parts = urlToUse.ToString().Split(new char[]{'?'}, 2);
string url = parts[0];
string data = parts[1];
var request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
var requestStream = request.GetRequestStream();
var requestStreamWriter = new StreamWriter(requestStream);
requestStreamWriter.Write(data);
requestStreamWriter.Close();
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
if (responseStream == null) return null;
var responseStreamReader = new StreamReader(responseStream);
var responseFromServer = responseStreamReader.ReadToEnd();
responseStreamReader.Close();
responseStream.Close();
response.Close();
Good luck with your quest.
I want to post a request on server using POST and webrequest?
I need to pass parameters as well while posting?
how can i pass the parameters while posting?
How can i do that???
Sample code...
string requestBody = string.Empty;
WebRequest request = WebRequest.Create("myursl");
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
//request.ContentLength = byte sXML.Length;
//System.IO.StreamWriter sw = new System.IO.StreamWriter(request.GetRequestStream());
//sw.Write(sXML);
//sw.Close();
HttpWebResponse res = (HttpWebResponse)request.GetResponse();
if (res != null)
{
using (StreamReader sr = new StreamReader(res.GetResponseStream(), true))
{
ReturnBody = sr.ReadToEnd();
StringBuilder s = new StringBuilder();
s.Append(ReturnBody);
sr.Close();
}
}
if (ReturnBody != null)
{
if (res.StatusCode == HttpStatusCode.OK)
{
//deserialize code for xml and get the output here
string s =ReturnBody;
}
}
NameValueCollection keyValues = new NameValueCollection();
keyValues["key1"] = "value1";
keyValues["key2"] = "value2";
using (var wc = new WebClient())
{
byte[] result = wc.UploadValues(url,keyValues);
}
you can try with this code
string parameters = "sample=<value>&other=<value>";
byte[] stream= Encoding.UTF8.GetBytes(parameters);
request.ContentLength = stream.Length;
Stream newStream=webRequest.GetRequestStream();
newStream.Write(stream,0,stream.Length);
newStream.Close();
WebResponse webResponse = request.GetResponse();
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.