I have this code in my website which is just a button and i'm trying to do a POST request to this api called schooltime https://schooltimeapp.docs.apiary.io/#introduction/requirements-for-apps-using-the-schooltime-api. Currently i'm trying to post 2 values into the REST api but i am currently having some trouble as my var = response keeps giving me this error System.Net.WebException: 'The remote server returned an error: (403) Forbidden. Any Help would be greatly appreciated thanks!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Web.Script.Serialization;
using System.IO;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Btn_Add_Click(object sender, EventArgs e)
{
var webRequest = (HttpWebRequest)WebRequest.Create("https://school-time.co/app2/index.php/api/students/");
var postData = "name=hello";
postData += "&email =world#test.com";
//add other attributes...
var data = Encoding.ASCII.GetBytes(postData);
webRequest.Method = "POST";
webRequest.Headers.Add("ST-API-KEY", "StRest#123");
webRequest.ContentType = "application/json";
using (var stream = webRequest.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)webRequest.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
}
Related
Hi I am using HttpWebRequest GET method to call a REST service. I am getting error :- ***'Content-Type' header must be modified using the appropriate property or method. Parameter name: name.***i checked all answer related this issue from stackoverflow.
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;
public partial class _Default : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
Getvalue(TextBox1.Text,TextBox2.Text,TextBox3.Text);
}
private void Getvalue(string text1, string text2, string text3)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "appication/json";
request.Headers.Add("Content-Type", "appication/json");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string myResponse = "";
using (System.IO.StreamReader sr = new system.IO.StreamReader(response.GetResponseStream()))
{
myResponse = sr.ReadToEnd();
}
Response.Write(myResponse);
}
}
I too ended up with this problem. But realized the issue is with how you setting the content type.
The proper way to set is
request.ContentType = "application/json";
I am using the below C#/ASP.net code to get the weather data from the api. The api link works if I copy/paste it on the browser, returns all the data I want .
But in my C# code, I get error "{"Unable to connect to the remote server"}"
Anyone knows what is wrong?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
using System.Runtime.Serialization;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Xml;
namespace WebApplication2
{
public partial class GetData : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
public static void getData()
{
var url = "http://api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID=e67fab67a2bc61c221e8a6165965c107";
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync(url).Result;
}
protected void Button1_Click(object sender, EventArgs e)
{
getData();
}
}
I'm not sure why you getting unable to connect remote server may be turning off your firewall solve your problem. try below code. https://stackoverflow.com/a/16642279/2745294
https://stackoverflow.com/a/5566981/2745294
string urlAddress = "http://api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID=e67fab67a2bc61c221e8a6165965c107";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = null;
if (response.CharacterSet == null)
{
readStream = new StreamReader(receiveStream);
}
else
{
readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
}
string data = readStream.ReadToEnd();
response.Close();
readStream.Close();
}
I noticed the issue was that my internet connection was using an internal dns server which its setting does not allow such a calls due to security restrictions. Outside our office, the code works just fine.
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 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?
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.