cURL in .NET application - c#

I have a cURL command provided by WooCommerce:
curl https://example.com/wp-json/wc/v2/orders \
-u consumer_key:consumer_secret
I'm using WebClient:
using (WebClient wc = new WebClient())
{
Uri url = new Uri("https://www.myhost.com/wp-json/wc/v2/orders");
System.Collections.Specialized.NameValueCollection reqparm = new System.Collections.Specialized.NameValueCollection();
reqparm.Add("consumer_key", keyValue);
byte[] responsebytes = wc.UploadValues(url, "POST", reqparm);
string responsebody = Encoding.UTF8.GetString(responsebytes);
}
But I'm getting this error:
IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
What have I done wrong here? I'm pretty sure my url and key are correct.
EDIT: Have just tried this as suggested by CmdrTchort and David:
using (WebClient wc = new WebClient())
{
wc.UseDefaultCredentials = true;
wc.Credentials = new NetworkCredential("consumer_key", keyValue);
string responsebody = wc.DownloadString("https://www.myhost.com/wp-json/wc/v2/orders");
}
Still receiving the same error.
EDIT: I have a suspicion I've been provided with invalid credentials I will update once this becomes clear...
I was given the wrong credentials. However that has not solved the issue.
I don't understand how consumer_key:consumer_secret is supposed to be represented in this request. There are two values: consumer_key and consumer_secret (I was only supplied with consumer_secret before, which I placed where keyValue is). I now assume that it is supposed to be of the form:
wc.Credentials = new NetworkCredential("consumer_key", "consumer_secret");
where "consumer_key" and "consumer_secret" represent the unique values provided. This does not work. This is starting to get slightly irritating.

You're posting the consumer_key:consumer_secret as part of a form POST, but that's not what cURL was doing. That looks more like a GET request with supplied authentication. Perhaps something like this:
wc.Credentials = new NetworkCredential("consumer_key", "consumer_secret");
and then making a GET request instead of a POST. With no values to upload, that part might be simplified. Maybe something like:
string responsebody = wc.DownloadString(url);

-u in curl passes the credentials as authorized headers and not as a dictionary of params.
You can add your credentials with :
wc.UseDefaultCredentials = true;
wc.Credentials = new NetworkCredential("username", "password");
Is your service responding and/or is it an untrusted or self-signed certificate?
If so , you can test ignoring the SSL-warning.
Btw, curl uses get by default (-X specifies method, which I can't see in your example) - so I'm assuming your only receiving by default and not actually posting values? If so you can use the DownloadString() directly.
So, if you're trying to get a file from this url you can do :
// IGNORE ALL SSL Certificates - would not do this in production
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(
delegate
{ return true; }
);
using (WebClient wc = new WebClient())
{
wc.UseDefaultCredentials = true;
wc.Credentials = new NetworkCredential("consumer_key", keyValue);
string responsebody = wc.DownloadString("https://www.myhost.com/wp-json/wc/v2/orders");
}

Related

download image from SharePoint Online using C#

I want to download Images from SharePoint Online site . Here is my code it will give webclient Exception.
var securedPassword = new SecureString();
foreach (var c in password.ToCharArray()) securedPassword.AppendChar(c);
var credentials = new SharePointOnlineCredentials(username, securedPassword);
DownloadFile(url, credentials, "https://damasjewellery.sharepoint.com/:i:/r/Products/Catalogue%20Images/BDR-001-NA-RG-X-0.JPG?csf=1&e=FclkOs");
DownloadFile Method Contains Webclient Object And Its DownloadFIle method. When I pass Url and path of Particular Images It will Give me an exception .
using (var client = new WebClient())
{
client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
client.Headers.Add("User-Agent: Other");
client.Credentials = credentials;
client.DownloadFile(webUrl, fileRelativeUrl);
}
A WebClient Exception usually means there's some kind of connection issue. Either the server returned a 404, the server timed out, there's no internet connection, or you're having a permissions issue.
*Edit: Realized the exception being thrown was already in the question.
Try swapping url to uri.
public void DownloadFile(
Uri address,
string fileName
)

C# HTTP request with proxy [duplicate]

I am using a web client class in my source code for downloading a string using http.
This was working fine. However, the clients in the company are all connected now to a proxy server. And the problem started from this.
When I have tested my application I don't think it can pass through the proxy server, as the exception that keeps getting thrown is "no response from xxx.xxx.xxx.xxx which is the proxy server IP address.
However, I can still navigate to the web site URL and it displays the string correctly in the browser when connecting through a proxy server, but not when I use my web client.
Is there something in the web client that I have to configure to allow me to access the url from behind a proxy server?
using (WebClient wc = new WebClient())
{
string strURL = "http://xxxxxxxxxxxxxxxxxxxxxxxx";
//Download only when the webclient is not busy.
if (!wc.IsBusy)
{
string rtn_msg = string.Empty;
try
{
rtn_msg = wc.DownloadString(new Uri(strURL));
return rtn_msg;
}
catch (WebException ex)
{
Console.Write(ex.Message);
return false;
}
catch (Exception ex)
{
Console.Write(ex.Message);
return false;
}
}
else
{
System.Windows.Forms.MessageBox.Show("Busy please try again");
return false;
}
}
My solution:
WebClient client = new WebClient();
WebProxy wp = new WebProxy(" proxy server url here");
client.Proxy = wp;
string str = client.DownloadString("http://www.google.com");
If you need to authenticate to the proxy, you need to set UseDefaultCredentials to false, and set the proxy Credentials.
WebProxy proxy = new WebProxy();
proxy.Address = new Uri("mywebproxyserver.com");
proxy.Credentials = new NetworkCredential("usernameHere", "pa****rdHere"); //These can be replaced by user input
proxy.UseDefaultCredentials = false;
proxy.BypassProxyOnLocal = false; //still use the proxy for local addresses
WebClient client = new WebClient();
client.Proxy = proxy;
string doc = client.DownloadString("http://www.google.com/");
If all you need is a simple proxy, you skip most of the lines above though. All you need is:
WebProxy proxy = new WebProxy("mywebproxyserver.com");
The answer proposed by Jonathan is proper, but requires that you specify the proxy credentials and url in the code. Usually, it is better to allow usage of the credentials as setup in the system by default (Users typically configure LAN Settings anyway in case they use a proxy)...
The below answer has been provided by Davide in earlier answer, but that requires modifying the app.config files. This solution is probably more useful since it does the same thing IN CODE.
In order to let the application use the default proxy settings as used in the user's system, one can use the following code:
IWebProxy wp = WebRequest.DefaultWebProxy;
wp.Credentials = CredentialCache.DefaultCredentials;
wc.Proxy = wp;
This will allow the application code to use the proxy (with logged-in credentials and default proxy url settings)... No headaches! :)
Hope this helps future viewers of this page to solve their problem!
I've encountered the same issue but using a webclient for downloading a file from the internet with a Winform application the solution was adding in the app.config:
<system.net>
<defaultProxy useDefaultCredentials="true" />
</system.net>
The same solution will work for an asp.net app inserting the same rows in web.config.
Hope it will help.
You need to configure the proxy in the WebClient object.
See the WebClient.Proxy property:
http://msdn.microsoft.com/en-us/library/system.net.webclient.proxy(VS.80).aspx
byte[] data;
using (WebClient client = new WebClient())
{
ICredentials cred;
cred = new NetworkCredential("xmen#test.com", "mybestpassword");
client.Proxy = new WebProxy("192.168.0.1",8000);
client.Credentials = cred;
string myurl="http://mytestsite.com/source.jpg";
data = client.DownloadData(myUrl);
}
File.WriteAllBytes(#"c:\images\target.jpg", data);
All previous answers have some merit, but the actual answer only needs ONE line:
wc.Proxy = new WebProxy("127.0.0.1", 8888);
where wc is the WebClient object, and 8888 is the port number of the proxy server located on the same machine.

Accessing HTTPS URL With Credentials

I have a HTTPS URL which i am trying to connect to but not able to and keep getting 401 unauthorized.
I tried to access the same URL over Web Browser (both at home and in company) and was able to connect to it. After i execute the HTTPS URL (which has some parameters in it like date etc) in the browser, it prompts for username and pwd and when i enter it, it gives the xml back in response.
I tried following segment of code on my home PC and it worked fine but when i tried same in office network, it gave me 407 error. I thereafter embedded the proxy code in it and now i don't get 407 rather i keep getting 401. Please help
Working Code on Home:
public static void WorkingCode()
{
string URL = "https://webservice.XYZ.com/display/?start_date=2015-05-06&end_date=2015-05-07";
Uri uri = new Uri(URL);
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential("username123", "Password123");
string results;
results = wc.DownloadString(uri);
Console.Write(results);
Console.Read();
}
Code within Organization with PROXY:
public static void WorkingCode()
{
string URL = "https://webservice.XYZ.com/display/?start_date=2015-05-06&end_date=2015-05-07";
Uri uri = new Uri(URL);
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential("username123", "Password123");
string results;
/* PROXY CODE*/
WebProxy myProxy = new WebProxy("frproxyseczom.PPP.com", 8080);
myProxy.UseDefaultCredentials = true;
wc.Proxy = myProxy;
/*---------------*/
results = wc.DownloadString(uri);
Console.Write(results);
Console.Read();
}
Because of security reasons, i have modified some details such as URL's, username and pwd.
You're probably getting a 401 in the proxy code because you're missing "http://" in the web proxy address.

c# webclient upload and download data from ssl

I have a wamp server on windows. SSL configured correctly. In browser it is working threw https: . I have a script test.php and I want to download and upload some POST data to it. I have my c# code:
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
NameValueCollection values = new NameValueCollection();
values.Add("paramtest", "testval");
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
byte[] result;
result = client.UploadValues("https://127.0.0.1./test.php", "POST", values);
string htmlCode = Encoding.UTF8.GetString(result);
textBox1.Text = htmlCode;
When runnign this code with http I got all the data. When put https, I got an error from the server:
400 Bad Request Bad Request
Your browser sent a request that this server could not
understand.
Have you got any idea how can I fix it?
Not sure whether this is the cause, but your url has a trailing '.' after the IP address:
try
result = client.UploadValues("https://127.0.0.1/test.php", "POST", values);
instead of
result = client.UploadValues("https://127.0.0.1./test.php", "POST", values);

webclient 401 into c#

I'm have some problems to use webclient.
When I try it:
var client = new WebClient();
client.Credentials = new NetworkCredential("intranet.homolog", "S3br#32011", "na-sebrae");
var html = client.DownloadData("http://www.intranet.sebrae.com.br/noticias/todas-as-notícias/rss.aspx?estado=");
I get an error (401).
This url returns xml feed, and, when I access it into browser, I login normally.
This user, and password are real.
Somebody have some ideia to I access it with the webclient?
Here's my guess: you're misusing the NetworkCredential constructor
The correct syntax is
public NetworkCredential(
string userName,
string password,
string domain
)
First username, then password, then domain - you got yours all wrong.
Try the following:
var client = new WebClient();
client.Credentials = new NetworkCredential("na-sebrae",
"S3br#32011", "intranet.homolog");
var html = client.DownloadData("http://www.intranet.sebrae.com.br" +
"/noticias/todas-as-notícias/rss.aspx?estado=");
I too get same error. The same link work better in browser but but giving 401 exception for WebClient.
string url = "http://www.intranet.sebrae.com.br/noticias/todas-as-notícias/rss.aspx?estado=";
var webClient = new WebClient();
webClient.Credentials = CredentialCache.DefaultCredentials;
byte[] html = webClient.DownloadData(fileAbsoluteUri);

Categories