Posting to Facebook - Graph API - c#

I have managed to successfully read my Facebook account by using the following code:
IAuthorizationState authorization = client.ProcessUserAuthorization();
if (authorization == null)
{
// Kick off authorization request
client.RequestUserAuthorization();
}
else
{
var request = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString(authorization.AccessToken));
Session["access_token"] = authorization.AccessToken;
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var graph = FacebookGraph.Deserialize(responseStream);
this.nameLabel.Text = HttpUtility.HtmlEncode(graph.Name);
}
}
}
I am now trying to POST to my Facebook news feed and I am struggling to find a guide to help me through it. I have tried to start it myself and for some reason it seems to throw back a 400: Bad Request error.
var request = WebRequest.Create("https://graph.facebook.com/me/feed?");
var postdata = "message=hello";
postdata += "&access_token" + Session["access_token"].ToString();
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();
Can anyone help me understand why my code is returning the error?

Use http://facebooksdk.net/ to make your job simple. Store access token and reuse for every request till it gets expired.

Related

Why same code sending different HTTP request in localhost and test server?

My code is sending a HTTP POST request with a JSON body. It is working
as expected in localhost but when I deploy it on server then it is
working differently. On my local machine response is okey but on server the response says request is not same !
var request = WebRequest.Create($"{baseUrl}{resourceAddress}");
request.Method = "POST";
request.ContentType = "application/json";
var json = JsonConvert.SerializeObject(requestBody);
request.ContentLength = json.Length;
using (var webStream = request.GetRequestStream())
{
using (var requestWriter = new StreamWriter(webStream, Encoding.ASCII))
{
requestWriter.Write(json);
}
}
try
{
var webResponse = request.GetResponse();
using var webStream = webResponse.GetResponseStream() ?? Stream.Null;
using var responseReader = new StreamReader(webStream);
var response = responseReader.ReadToEnd();
var paymentUrlResponse = JsonConvert.DeserializeObject<PaymentUrlResponse>(response);
if(paymentUrlResponse.Result.ResultCode != "00")
{
throw new Exception("Failed to get URL. Http Response: OK , Result Code: " + paymentUrlResponse.Result.ResultCode);
}
_httpContextAccessor.HttpContext.Response.Redirect(redirectionUrl);
}

Paypal HTTP post request gives Invalid Merchant or Merchant doesn't exist error in MVC C#

I am facing trouble in making an HTTP post request to Paypal for Secure token to use Paypal's Hosted solution but I am getting this error:
Some required information is missing or incorrect. Please correct the fields below and try again.
Error: Invalid Merchant or Merchant doesn't exist!
This is my C# code throught which I am making HTTP calls:
string strNVP = "https://pilot-payflowpro.paypal.com?PARTNER=PayPal&USER=myUsername&VENDOR=myVendorName&PWD=myPassword&TRXTYPE=A&AMT=" + obj.CurrentPackagePrice + "&CREATESECURETOKEN=Y&SECURETOKENID=" + Guid.NewGuid().ToString("N");
HttpWebRequest wrWebRequest = (HttpWebRequest)WebRequest.Create(strNVP);
wrWebRequest.Method = "POST";
StreamWriter requestWriter = new StreamWriter(wrWebRequest.GetRequestStream());
requestWriter.Write(strNVP);
requestWriter.Close();
HttpWebResponse hwrWebResponse = (HttpWebResponse)wrWebRequest.GetResponse();
StreamReader responseReader = new StreamReader(wrWebRequest.GetResponse().GetResponseStream());
//and read the response
string responseData = responseReader.ReadToEnd();
responseReader.Close();
string result = Server.UrlDecode(responseData);
string[] arrResult = result.Split('&');
Hashtable htResponse = new Hashtable();
string[] responseItemArray;
foreach (string responseItem in arrResult)
{
responseItemArray = responseItem.Split('=');
htResponse.Add(responseItemArray[0], responseItemArray[1]);
}
string responseResult = htResponse["RESULT"].ToString();
string response = htResponse["RESPMSG"].ToString();
///for Success response
if (responseResult == "0" && response == "Approved")
{
ViewBag.secureToken = htResponse["SECURETOKEN"].ToString();
ViewBag.secureTokenId = htResponse["SECURETOKENID"].ToString();
}
Kindly help me in this problem may b I have done some wrong in my code above also.
The issue was that I was unable to receive a Token and TokenID due to that this exception was arising and then I resolved my issue by making modifications in the above code so that the Paypal sends back a response with Token and TokenID which I used in iframe and its working perfect now.
var request = (HttpWebRequest)WebRequest.Create("https://pilot-payflowpro.paypal.com");
var postData = "PARTNER=PayPal&USER=myUser&VENDOR=myVendor&PWD=myPassword&TRXTYPE=A&AMT=50&CREATESECURETOKEN=Y&SECURETOKENID=" + Guid.NewGuid().ToString("N");
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 responseData = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(responseData.GetResponseStream()).ReadToEnd();
string result = Server.UrlDecode(responseString);
string[] arrResult = result.Split('&');
Hashtable htResponse = new Hashtable();
string[] responseItemArray;
foreach (string responseItem in arrResult)
{
responseItemArray = responseItem.Split('=');
htResponse.Add(responseItemArray[0], responseItemArray[1]);
}
string responseResult = htResponse["RESULT"].ToString();
string response = htResponse["RESPMSG"].ToString();
///for Success response
if (responseResult == "0" && response == "Approved")
{
ViewBag.secureToken = htResponse["SECURETOKEN"].ToString();
ViewBag.secureTokenId = htResponse["SECURETOKENID"].ToString();
}
The above code is buggy and throws exceptions while receiving a response etc. So this code block is working good.

Web Request Not Returning Anything

I'm trying to login to this website here: https://freebitco.in/
So I set up a web request like so:
var request = (HttpWebRequest)WebRequest.Create("https://freebitco.in");
var postdata = "op=login&btc_address=BTCADDRESS&password=PASSWORD";
var data = Encoding.ASCII.GetBytes(postdata);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length; //1PkhThc9hCXpdvcThtwX3SzbfmTzDFxL1h:bigken <= BTC Login
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
MessageBox.Show(responseString);
The messagebox returns to me nothing though, blank. I'm not sure why this is happening so I was hoping someone could shed some light on this? I've also tried using a Web Client, and it gave me the same result. Thank you guys.
EDIT: Here's the Fiddler Raw data: http://pastebin.com/WUEvq6D5
Edit 2: Tried encoding the POST data and now it returns the login page
Updated Code:
var request = (HttpWebRequest)WebRequest.Create("https://freebitco.in");
var postdata = "op=login&btc_address=ADDRESS&password=PASS";
var encoded_data = HttpUtility.UrlEncode(postdata);
var data = Encoding.ASCII.GetBytes(encoded_data);
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();

Testing multiple parameters web api c# - fiddler

I need help.
I have a method: PostCustomer
HttpResponseMessage PostCustomer([FromBody] CustomerRec Logs, [FromBody] Customer customer)
Now my problem is how will I able to test this through fiddler
I know I need to call for example:
"//api/customer/PostCustomer"
But how will I pass parameters on this?
I'm testing this using fiddler.
I'm not sure if you are asking how to build the url request (passing the parameters for your method through url)
If that's it, it should be like this
api/customer/PostCustomer/?FirstParameter=Example&SecondParemeter=Example2
If you mean the request itself
string postData = string.Format("?FirstParameter=" + txt_First.Text + "&SecondParemeter=" + txt_Last.Text);
byte[] data = Encoding.UTF8.GetBytes(postData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("..../api/customer/PostCustomer"/" + postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "application/json";
request.ContentLength = data.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(data, 0, data.Length);
}
try
{
using (WebResponse response = request.GetResponse())
{
var responseValue = string.Empty;
// grab the response
using (var responseStream = response.GetResponseStream())
{
using (var reader = new StreamReader(responseStream))
{
responseValue = reader.ReadToEnd(); // read the full response
}
}
if (responseValue != "")
{
//Do something here if response is not empty
}
}
}
catch (WebException ex)
{
// Handle error
}
PS: Can't comment on post because it asks for 50+ reputation...

Get access token from google oauth from code

i used following code to get the access token from code as below
String code = HttpContext.Current.Request["code"];
string redirecturl = HttpContext.Current.Request["url"];
string Url = "https://accounts.google.com/o/oauth2/token";
string grant_type = "authorization_code";
string redirect_uri_encode = UrlEncodeForGoogle(url);
string data = "code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type={4}&access_type={5}";
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
string result = null;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
string param = string.Format(data, code,configurationInfo.oauthclientid , configurationInfo.oauthclientsecretid, redirect_uri_encode, grant_type, "offline");
var bs = Encoding.UTF8.GetBytes(param);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse response = request.GetResponse())
{
var sr = new StreamReader(response.GetResponseStream());
result = sr.ReadToEnd();
sr.Close();
}
i am getting response as
The remote server returned an error: (400) Bad Request.
i do not know where i went wrong
waiting for your valuable comments
Google also provides a higher level library for accessing its services. I find it makes it much easier to work with its APIs.
http://code.google.com/p/google-api-dotnet-client/

Categories