I keep on getting the exception The remote server returned an error: (400) Bad Request. Whenever it comes at the HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;. Can someone please help me? Here's my code. By the way, it's just a single aspx with not html content. It's just a pure C# file:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Facebook;
namespace Facebook_API
{
public partial class Facebooksync : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CheckAuthorization();
}
private void CheckAuthorization()
{
string app_id = "1234567891234567"; //Just placed this digits to keep this hidden
string app_secret = "12345678912345678912345678912345"; //Just placed this digits to keep this hidden
string scope ="publish_stream,manage_pages"; //Scope are the permissions
if( Request["code"] == null)
{
Response.Redirect(String.Format(
"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope));
}
else
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format(
"https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret{4}",
app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using(HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach(string token in vals.Split('&'))
{
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1 ));
}
}
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
client.Post("/me/feed", new { message = "Testing Facebook WebAPI " });
}
}
}
You can also try this code by simple creating a new project and create a webform the just insert this in the cs file.
Why are you using
request.Method = "Put";
instead of a normal GET request?
Related
the APi call (Patch) through Visual Studio Console app is failing with the following error
The remote server returned an error: (403) Forbidden.
The same call works fine when I use Postman. I get the response back from Postman(Basic authentication with username and password). What could be the issue with the c# program.
.NET framework 4.7
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Xml;
using System.Web;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var result = string.Empty;
string json = #"{
""schemas"": [
""urn:scim:schemas:core:2.0:User"",
""urn:scim:schemas:extension:fa:2.0:faUser""
],
""userName"": ""ZMatt.Dandon #cmpy.com"",
""name"": {
""familyName"": ""Dandon"",
""givenName"": ""ZMatt""
},
""displayName"": ""ZMatt Dandon"",
""preferredLanguage"": ""en"",
""active"": false
}";
string url = #"https://url/hcmRestApi/scim/Users/C8FF94E381891376E050480A69294891";
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// Making Web Request
HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(url);
Req.Credentials = new NetworkCredential("UserName", "Password");
//Content_type
Req.ContentType = "application/vnd.oracle.adf.action+json";
//HTTP method
Req.Method = "PATCH";
using (var streamWriter = new StreamWriter(Req.GetRequestStream()))
{
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)Req.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
}
}
}
Basic authentication is base64 encoded and added to the HTTP Authorization header.
// Making Web Request
HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(url);
//Req.Credentials = new NetworkCredential("00OracleERPuser", "PMT12345");
string encoded = System.Convert.ToBase64String(Encoding.GetEncoding("UTF-8")
.GetBytes("UserName" + ":" + "Password"));
Req.Headers.Add("Authorization", "Basic " + encoded);
i refereed this post
how to post to facebook page wall from .NET but it will work on facebook page to post as visitor post.
and i want to post of page timeline not at visitor post and i am admin of this page and app.
please give solution for it .
here in my code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Facebook;
using System.Dynamic;
public partial class facebook : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
authontication();
}
private void authontication()
{
string app_id = "**********************";
string app_secret = "###################################";
string scope = "publish_actions,manage_pages";
if (Request["code"] == null)
{
Response.Redirect(string.Format(
"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope));
}
else
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);
HttpWebRequest request = System.Net.WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
//meh.aspx?token1=steve&token2=jake&...
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
//dynamic parameters = new ExpandoObject();
string name = "sudhanshu";
name += " new data";
client.Post("/1168908853153698/feed", new { message = "My first appProduct "+name+" ." });
}
}
}
You need to use a Page Token, not a User Token. Make sure it really is a Page Token by debugging it: https://developers.facebook.com/tools/debug/accesstoken/
Also, publish_actions is the wrong permission to post as Page, you need to use publish_pages.
Additional information:
http://www.devils-heaven.com/facebook-access-tokens/
https://developers.facebook.com/docs/facebook-login/access-tokens
https://developers.facebook.com/docs/graph-api/reference/v2.6/page/feed#publish
I'm trying to post a JSON string on a PHP page using HTTP response methods as follows:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;
using System.Web;
namespace http_requests
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost/abc/products.php");
//httpWebRequest.ContentType = "application/json";
//httpWebRequest.Method = "POST";
//using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
//{
// string json = new JavaScriptSerializer().Serialize(new
// {
// user = "Foo",
// password = "Baz"
// });
// streamWriter.Write(json);
// streamWriter.Flush();
// streamWriter.Close();
// var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
// using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
// {
// var result = streamReader.ReadToEnd();
// }
//}
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost/ABC/products.php");
request.Method = WebRequestMethods.Http.Post;
string DataToPost = new JavaScriptSerializer().Serialize(new
{
user = "Foo",
password = "Baz"
});
byte[] bytes = Encoding.UTF8.GetBytes(DataToPost);
string byteString = Encoding.UTF8.GetString(bytes);
Stream os = null;
//string postData = "firstName=" + HttpUtility.UrlEncode(p.firstName) +
request.ContentLength = bytes.Length;
request.ContentType = "application/x-www-form-urlencoded";
os = request.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
//StreamWriter writer = new StreamWriter(request.GetRequestStream());
//writer.Write(DataToPost);
//writer.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//StreamReader reader = new StreamReader(response.GetResponseStream());
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
richTextBox1.AppendText("R : " + result);
Console.WriteLine(streamReader.ReadToEnd().Trim());
}
//richTextBox1.Text = response.ToString();
}
}
}
I tried it in many different ways (converting to bytes too) but still posts a NULL array.
PHP Code:
<?php
$json = $_POST;
if (isset($json)) {
echo "This var is set so I will print.";
//var_dump($json);
var_dump(json_decode(file_get_contents('php://input')));
}
?>
When I try to get tha response from server and print onto a text box, it prints right:
R : This var is set so I will print.object(stdClass)#1 (2) {
["user"]=>
string(3) "Foo"
["password"]=>
string(3) "Baz"
}
but i'm unable to check it on my PHP page, it says:
This var is set so I will print.NULL
Not sure if its posting a JSON onto PHP or not, but it sure does posts a NULL.
I want to see the JSON on PHP page, Any help would be appreciated.
Thank you,
Revathy
There is nothing wrong with your c# client side code, the problem is that visiting a site in your browser is a seperate request from the c# post, so you wont see anything.
As per my comment, if you want to see the data in a browser after a post i c#, you will need to save and retrieve it.
Here is a simple example using a text file to save post data and display it:
//if post request
if($_SERVER['REQUEST_METHOD']=='POST'){
//get data from POST
$data = file_get_contents('php://input');
//save to file
file_put_contents('data.txt', $data);
die('Saved');
}
//else if its a get request (eg view in browser)
var_dump(json_decode(file_get_contents('data.txt')));
I have a big trouble. I've done an e-commerce site many month ago, now i wanna do that after an user has bought, paypal redirect the user in a website that confirm the bought with an e-mail.
Obviously, the return page has a control of refererpage, because it can't send a confirmation mail to all that write the page address, but the command:
Request.ServerVariables["HTTP_REFERER"]
Doesn't work, because paypal is an https webpage. So, how i can solve it?
Thank you before!
hi you can try below code for this:
First set the "notify_url" in your website
<input type="hidden" name="notify_url" value="http://www.your-website-url.com/notifypaypal.aspx" />
after that create notifypaypal.aspx Page.
notifypaypal.aspx : here not required any code ..
notifypaypal.aspx.cs :
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Threading;
using System.Net;
using BLL;
public partial class notifypaypal : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Post back to either sandbox or live
// string strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr";//For localhost
string strLive = "https://www.paypal.com/cgi-bin/webscr";//For live server
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strLive);
//Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] param = Request.BinaryRead(HttpContext.Current.Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(param);
string ipnPost = strRequest;
strRequest += "&cmd=_notify-validate";
req.ContentLength = strRequest.Length;
//for proxy
//WebProxy proxy = new WebProxy(new Uri("http://url:port#"));
//req.Proxy = proxy;
//Send the request to PayPal and get the response
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();
// logging ipn messages... be sure that you give write permission to process executing this code
string logPathDir = ResolveUrl("Messages");
string logPath = string.Format("{0}\\{1}.txt",Server.MapPath(logPathDir), DateTime.Now.Ticks);
File.WriteAllText(logPath, ipnPost);
if (strResponse == "VERIFIED")
{
#region [Update Order Status]
string txn_id = HttpContext.Current.Request["txn_id"]; //txn_id= Unique transaction number.
string payment_status = HttpContext.Current.Request["payment_status"]; //payment_status=Payment state(Completed,Pending,Failed,Denied,Refunded)
string pending_reason = HttpContext.Current.Request["pending_reason"]; //pending_reason=Reason of payment delay(echeck,multi_currency,intl,verify,...)
string item_number = HttpContext.Current.Request["item_number"]; //item_number=order number
if (HttpContext.Current.Request["payment_status"].ToString() == "Completed")
{
try
{
//update in database that particular "item_number"(Order number) is successfully Completed
}
catch
{
}
}
else
{
if (HttpContext.Current.Request["payment_status"].ToString() == "Pending")
{
try
{
//update in database that particular "item_number"(Order number) is Pending
}
catch
{
}
}
else
{
}
}
#endregion
}
else if (strResponse == "INVALID")
{
}
else
{
}
}
}
I’m using bing’s api TTS, I get the information from: http://msdn.microsoft.com/en-us/library/ff512420.aspx
This is the code (from the webside):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Media;
namespace Apigoogleprova
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
Speak();
}
private static void ProcessWebException(WebException e, string message)
{
Console.WriteLine("{0}: {1}", message, e.ToString());
// Obtain detailed error information
string strResponse = string.Empty;
using (HttpWebResponse response = (HttpWebResponse)e.Response)
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(responseStream, System.Text.Encoding.ASCII))
{
strResponse = sr.ReadToEnd();
}
}
}
Console.WriteLine("Http status code={0}, error message={1}", e.Status, strResponse);
}
public static void Speak()
{
string appId = "myappID"; //go to http://msdn.microsoft.com/en-us/library/ff512386.aspx to obtain AppId.
string text = "speak to me";
string language = "en";
string uri = "http://api.microsofttranslator.com/v2/Http.svc/Speak?&appId=" + appId +"&text;=" + text + "&language;=" + language;
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
//httpWebRequest.Proxy = new WebProxy(""); set your proxy name here if needed
WebResponse response = null;
try
{
response = httpWebRequest.GetResponse();
using (Stream stream = response.GetResponseStream())
{
using (SoundPlayer player = new SoundPlayer(stream))
{
player.PlaySync();
}
}
}
catch (WebException e)
{
//ProcessWebException(e, "Failed to speak");
MessageBox.Show("Error"+e);
}
finally
{
if (response != null)
{
response.Close();
response = null;
}
}
}
}
}
(I changed “myappID” with the ID that has provided me Microsoft)
When I run the app I get the following error:
Remote Server Error (400) Bad Request
I tried to go to the web with my browsers (firefox, chrome and IE):
http://api.microsofttranslator.com/v2/Http.svc/Speak?&appId=myappID&text;=speak to me&language;=en
And the result is:
**Argument Exception**
Method: Speak()
Parameter: text Message: Value cannot be null.
Parameter name: text message
id=3835.V2_Rest.Speak.25BD061A
Anyone know how to solve this problem?
Thank you very much!
Remove the ; from the parameter names in the query string.