Not found error when using WebClient to send a GET request - c#

I'm trying to send GET request to my server, using WebClient and get error for "Not found". In C++ the same request works fine. My URL looks like:
"https://www.example.com/something/something&param1=data1&param2={}"
... and the request look like
WebClient client = new WebClient();
string res = client.DownloadString(url);
What am I doing wrong?

I succeeded! i was missing the headers.
my URL looks like "https://www.example.com/something/something?param1=data1&param2={}"
WebClient client = new WebClient();
client.Headers.Add("Content-Type", "application/json");
client.Headers.Add("Accept-Version", "4");
client.Headers.Add("User-Agent", "v4.1.0.0");
string res = client.DownloadString(url);
Thanks for the help

Related

Receive data from server using POST method and with a request body using WebClient in C#

I am trying to receive data back from the server using POST method and the request should have a body. I am using WebClient for this and trying to get the response back in string. I know we can use HttpClient to achieve this. But I want to use WebClient for this specific instance.
I went through this post and tried UploadString and the response gives me a 400 BAD Request.
using (var wc = new WebClient())
{
wc.Headers.Add("Accept: application/json");
wc.Headers.Add("User-Agent: xxxxxxx");
wc.Headers.Add($"Authorization: Bearer {creds.APIKey.Trim()}");
var jsonString = JsonConvert.SerializeObject(new UserRequestBody
{
group_id = userDetails.data.org_id
});
var response = wc.UploadString("https://api.xxxxx.yyy/v2/users", "POST", jsonString);
}
I tested the end point using Postman (with the request header having an api key and the request body in JSON) and it works fine.
I know I haven't formatted the request right. Can someone please help me.
Big Thanks to #Santiago Hernández. The issue was using wc.Headers.Add("Accept: application/json"); in the request header. Changing it to wc.Headers.Add("Content-Type: application/json"); returned a 200 Ok response. The code modification is as follows
using (var wc = new WebClient())
{
wc.Headers.Add("Content-Type: application/json");
wc.Headers.Add("User-Agent: xxxxxxx");
wc.Headers.Add($"Authorization: Bearer {creds.APIKey.Trim()}");
var jsonString = JsonConvert.SerializeObject(new UserRequestBody
{
group_id = userDetails.data.org_id
});
var response = wc.UploadString("https://api.xxxxx.yyy/v2/users", "POST", jsonString);
}
Accept tells the server the kind of response the client will accept and Content-type is about the payload/content of the current request or response. Do not use Content-type if the request doesn't have a payload/ body.
More information about this can be found here.

WebService Call from .net C# getting error : (502) Bad Gateway

Trying to call WebServices from C# and getting below error:
System.Net.WebException: 'The remote server returned an error: (502) Bad Gateway
Code:
WebRequest request = WebRequest.Create("https://xxxxx/cgi/webservice.pl?function=get_latest_ts_values&site_list=130105B&datasource=AT&varfrom=10.00&varto=10.00&lookback=60&format=csv");
request.Method = "GET";
WebResponse response = request.GetResponse();
using (Stream dataStream = response.GetResponseStream() )
{
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
Console.ReadLine();
}
But works fine when i use Postman or just copy url in browser and also works fine with below python code:
import requests
dataload = {}
dataurl = "https://xxxxx/cgi/webservice.pl?function=get_latest_ts_values&site_list=130105B&datasource=AT&varfrom=10.00&varto=10.00&lookback=60"
headers = {}
response = requests.request("GET", dataurl, headers=headers, data=dataload)
for dataresp in response:
print(dataresp)
What am I doing wrong with C# code?
The uri for the WebRequest has the query parameter &format=csv. Maybe this is why you are getting a 502. The Python request is missing that query parameter. Did you try the WebRequest by removing that part?
Could be incorrect content type or user agent having the wrong information. Postman could be setting these values without your knowledge. Might try in the exception seeing if there is a a response stream and read it through a streamreader to see if there is any more information you're not seeing to point you in the correct direction.
Ended up using RestSharp and it works fine. (https://www.nuget.org/packages/RestSharp)
string Uri = "https://xxxx/cgi/webservice.pl?xxxx";
var client = new RestSharp.RestClient(Uri);
client.Timeout = -1;
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

Using WebClient keeps changing json to text/plain for Content-Type

I'm using WebClient and I set the headers to JSON yet when I look at Fiddler, it shows text/plain. I do not understand why. I have to use WebClient (older app).
How do I enforce JSON to be sent in the request as Content-Type?
My relevant code:
var webClient = new WebClient();
webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
webClient.Headers.Add("cache-control", "no-cache");
webClient.Headers.Add("Bearer", token);
//further down to the call...
var content = JsonConvert.SerializeObject(request).Replace(#"\\\", #"\");
var jsonResponse = webClient.UploadString($"https://{APIHost}{APIAddress}", content.ToString());

Python urllib with proxy not working while C# works

I am trying to get data from an API using python 'urllib.request'. My requests sometime need to post json data.
My network is behind a proxy
When i try to get the data using C# code, everything works great:
WebClient wc = new WebClient();
WebProxy wp = new WebProxy("{IP}", 8080);
wc.Proxy = wp;
var request = "https://{API address and params}";
Uri serviceUri = new Uri(request);
string download = wc.DownloadString(serviceUri);
My python code is:
import urllib
address = "https://{API address and params}"
req = urllib.request.Request(address)
req.set_proxy("{IP}:8080", "http")
response = urllib.request.urlopen(req)
My python code throws a 400 error code exception - 'bad request'
What am i doing wrong?

How to handle C# .NET POST and GET commands

The current project I am working on requires a 2 way communication from the bot to my website.
Supposing the example URL is www.example.com/foobar.php or something, can you explain me how to POST and GET data from there?
Thanks a lot.
P.S. - Using webclient right?
I'd suggest using RestSharp. It's a lot easier than using WebClient, and gives you a lot more options:
var client = new RestClient("http://www.example.com/");
//to POST data:
var postRequest = new RestRequest("foo.php", Method.POST);
postRequest.AddParameter("name", "value");
var postResponse = client.Execute(postRequest);
//postResponse.Content will contain the raw response from the server
//To GET data
var getRequest = new RestRequest("foo.php", Method.GET);
getRequest.AddParameter("name", "value");
var getResponse = client.Execute(getRequest);
Yes, you can use WebClient:
using (WebClient client = new WebClient())
{
NameValueCollection nvc = new NameValueCollection()
{
{ "foo", "bar"}
};
byte[] responseBytes = client.UploadValues("http://www.example.com/foobar.php", nvc);
string response = System.Text.Encoding.ASCII.GetString(responseBytes);
}
You can use WebClient
Look up method UploadString and DownloadString

Categories

Resources