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.
Related
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();
}
}
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 have following program which get more then 1,00,000 urls from database and use C# HttpWebRequest object to get Response and save into database.
To get response of 1,00,000 urls take long time to run in single server. I want divide this process into thread and want run in multiple server.
It is possible to use such type of code in MapReduce in C# with thread and TPL ?
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization.Json;
using System.Net;
using System.Runtime.Serialization;
using System.IO;
namespace Test
{
class Program
{
static void Main(string[] args)
{
TestApp testapp = new TestApp();
var urls = testapp.GetURls();
//get string from urls
foreach (var url in urls)
{
var responseString=testapp.GetURLString(url);
//now save response into database
testapp.saveResponseToDB(responseString);
}
}
}
public class TestApp
{
public void saveResponseToDB(string response)
{
//save into db
}
public List<string> GetURls()
{
var urls =new List<string>();
//fetching more then 100000 urls from database.
return urls;
}
public string GetURLString(string requestUrl)
{
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
// Read the content.
string responseFromServer = reader.ReadToEnd();
// return the content.
return responseFromServer;
}
}
}
}
I wanted to create a program in C# that goes to a website, with the use of a proxy server.
If I run this program I got error at line 37 when I debug it. Can you help me please?
I always got the error that the time is occuperd. I changed TimeOut, but
It never does anything.
txtUrl is a textbox where you need to put in the url of the website you wanna visite.
txtProxyPath is a textbox that is used as a openfiledialog,
and there I can select a .txt file with proxy ips in.
Here the code I used:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace YoutubeRefresh
{
public partial class Form1 : Form
{
static private ArrayList listProxy = new ArrayList();
static private short proxyShort = 0;
public Form1()
{
InitializeComponent();
}
private void btnStart_Click(object sender, EventArgs e)
{
Uri uriAdress = new Uri(txtUrl.Text);
object[] arrayProxy = listProxy.ToArray();
WebProxy proxyObject = new WebProxy(arrayProxy[proxyShort].ToString());
MessageBox.Show("Proxyserver used: " + arrayProxy[proxyShort].ToString());
proxyShort += 1;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(txtUrl.Text);
webRequest.Proxy = proxyObject;
// httpwepresponse error
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream receiveStream = response.GetResponseStream();
webBrowser1.DocumentStream = receiveStream;
}
private void btnChoosListProxy_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
txtProxyPath.Text = openFileDialog1.FileName;
}
foreach (var v in File.ReadAllLines(txtProxyPath.Text))
{
listProxy.Add(v.ToString());
}
}
}
}
Thank you very much!
var request = (HttpWebRequest)WebRequest.Create("http://google.com");
request.Proxy = new WebProxy("IP", port);
var response = (HttpWebResponse)request.GetResponse();
using (var stream = response.GetResponseStream())
{
if (stream != null)
{
using (var streamReader = new StreamReader(stream))
{
Console.WriteLine(streamReader.ReadToEnd());
}
}
}
Also in your App.Config file, (if you don't have one, create one) add the following.
<configuration>
<system.net>
<settings>
<servicePointManager expect100Continue="false"/>
</settings>
</system.net>
</configuration>
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.