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!
Related
I'm trying to make POST to an external webapi sending "raw" data. I could successfully do it using for example Postman, but when I tried to do it in my MVC App, I get the following error: Specified value does not have a ':' separator. Parameter name: header.
This is my code for calling the webapi:
public UserCustom GetUserByToken(string pToken)
{
ResponseLogin vRespuesta = new ResponseLogin();
UserCarmocal vUsuarioFinal = null;
string vApiKey = ConfigurationManager.AppSettings["ApiKey"];
string vDirUser = ConfigurationManager.AppSettings["EndpointUsr"];
WebRequest request = WebRequest.Create(vDirUser);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.Headers.Add("ApiKey", vApiKey);
string postData = pToken;
//I THINK THE ERROR IS IN THE NEXT LINE:
request.Headers.Add(postData);
using (Stream s = request.GetResponse().GetResponseStream())
{
using (StreamReader sr = new StreamReader(s))
{
vRespuesta = new JavaScriptSerializer().Deserialize<ResponseLogin>(sr.ReadToEnd());
if (vRespuesta.status == "success")
{ vUsuarioFinal.FirstName = "Test"; }
}
}
return vUsuarioFinal;
}
Write the pToken variable to request stream
PSUEDO CODE
public UserCustom GetUserByToken(string pToken)
{
ResponseLogin vRespuesta = new ResponseLogin();
UserCarmocal vUsuarioFinal = null;
string vApiKey = ConfigurationManager.AppSettings["ApiKey"];
string vDirUser = ConfigurationManager.AppSettings["EndpointUsr"];
WebRequest request = WebRequest.Create(vDirUser);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.Headers.Add("ApiKey", vApiKey);
var bytes = System.Text.Encoding.UTF8.GetBytes(pToken);
var stream = request.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Flush();
using (Stream s = request.GetResponse().GetResponseStream())
{
using (StreamReader sr = new StreamReader(s))
{
vRespuesta = new JavaScriptSerializer().Deserialize<ResponseLogin>(sr.ReadToEnd());
if (vRespuesta.status == "success")
{ vUsuarioFinal.FirstName = "Test"; }
}
}
return vUsuarioFinal;
}
I have the access token. How can I make a request using the token in c#?
Here is what I have tried unsuccessfully resulting in error 400 Bad Request.
Note: the url was copied from the YQL console
public static void Request(string token)
{
var request =
WebRequest.Create(
#"https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20fantasysports.leagues%20where%20league_key%3D'371.l.4019'&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys");
request.Headers["Authorization"] = $"Bearer {token}";
request.Method = "GET";
request.ContentType = "application/xml;charset=UTF-8";
using (var response = request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
if (stream == null) return;
var reader = new StreamReader(stream, Encoding.UTF8);
var responseString = reader.ReadToEnd();
}
}
}
WebRequest request = WebRequest.Create(url);
WebRequest.DefaultWebProxy = null;
request.Proxy = null;
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
using (StreamReader sr = new StreamReader(data))
{
html = sr.ReadToEnd();
}
The above code not able to read/download the following webpages:
1) https://en.wikipedia.org/wiki/Unified_Payments_Interface
2) http://www.npci.org.in/UPI_Background.aspx
This may help you below code contains for both to get and post data:
public static string PostContent(this Uri url, string body, string contentType = null)
{
var request = WebRequest.Create(url);
request.Method = "POST";
if (!string.IsNullOrEmpty(contentType)) request.ContentType = contentType;
using (var requestStream = request.GetRequestStream())
{
if (!string.IsNullOrEmpty(body)) using (var writer = new StreamWriter(requestStream)) { writer.Write(body); }
using (var response = request.GetResponse() as HttpWebResponse)
{
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
}
public static string GetContent(this Uri url)
{
WebClient client = new WebClient();
try
{
using (client)
{
client.Encoding = Encoding.UTF8;
return client.DownloadString(url);
}
}
catch (WebException)
{
return "";
}
finally
{
client.Dispose();
client = null;
}
}
please note that .aspx file extension design the server-side page and in consequence you will be able to download only the html page that display when you navigate on these sites (this is the same for .php files).
but if you want to download the frontend view this should work :
using System.Net;
...
WebClient client = new WebClient();
client.DownloadFile("Your url","download location");
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
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.