I want to upload a file with WebClient.UploadFile and is as
string proxyserver = "http://10.0.0.127:8080/";
IWebProxy proxy = new WebProxy(proxyserver);
proxy.Credentials = CredentialCache.DefaultCredentials;
WebClient Client = new WebClient();
Client.Headers.Add("UA-CPU", "x86");
Client.Headers.Add("Accept-Language", "en-us");
Client.Headers.Add("Cache-Control", "no-cache");
Client.Proxy = proxy;
byte[] rawResponse = Client.UploadFile(uri, filename);
string response = System.Text.Encoding.ASCII.GetString(rawResponse);
I am getting remote server returned an error 403 Forbidden and if i comment the proxy i am able to get response, but i can't see response in fiddler, not knowing why? and also how can i work this with proxy
Related
I have been trying to make a post request with C# using Webclient. I was getting 400 bad request.When I adjusted the headers, and added authorization to it,I started getting 401 authorization error.Now i commented out the authorization, 400 bad request is back. So my question is: when it was returning 400, does it mean the server authenticated me and that something might be wrong with my json or can 400 be returned even before authentication is done? Below is my code.
public static string Post(string json, string encoded){
try{
string url = "https://blah/rest/api/blah";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var client = new WebClient();
client.Encoding = Encoding.UTF8;
IWebProxy wp = WebRequest.DefaultWebProxy;
wp.Credentials = CredentialCache.DefaultCredentials;
client.Proxy = wp;
//client.Headers[HttpRequestHeader.Authorization] = "Basic " + encoded;
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.Headers[HttpRequestHeader.Accept] = "application/json";
var response = client.UploadString(url, "POST",json);
return response
}
catch(Exception e){
return e
}
}
I need to consume web service that requires basic pre-emptive authentication. I have below code, but getting an error on response -
'The remote server returned an error: (403) Forbidden.'
User credentials are correct. Any ideas what is wrong?
string url = "MYURL";
HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;
string user = "USER";
string pwd = "PASSWORD";
string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(user + ":" + pwd));
req.PreAuthenticate = true;
req.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
req.Headers.Add("Authorization", auth);
WebResponse resp = req.GetResponse();
resp.Close();
req = HttpWebRequest.Create(url) as HttpWebRequest;
req.PreAuthenticate = true;
req.Credentials = new NetworkCredential(user, pwd);
resp.Close();
401 is the error code you receive when you could not be authenticated (i.e. it's unclear who you are). If you get a 403 that means the server knows who you are but still thinks you should not be allowed access.
I guess you should talk to whoever provided you with the credentials and ask him.
I'm looking to get the content of a page from
http://12.18.60.199:81
I'm using my corporate network and if I use internet explorer, it prompts for username and password, I type that in and I get the content of the page. I need to do this in C#, but have no luck for the past few hours:
Uri requestUri = null;
Uri.TryCreate("http://12.18.60.199:81", UriKind.Absolute, out requestUri);
NetworkCredential nc = new NetworkCredential(#"username", #"password", "domain");
CredentialCache cache = new CredentialCache();
cache.Add(requestUri, "Basic", nc); //also tried "Anonymous", "Basic", "Digest", "Dpa",
//"External", "Kerberos", "Msn", "Negotiate", "Ntlm", "Sicily"
using (WebClient client = new WebClient())
{
client.Credentials = cache;
using (Stream stream = client.OpenRead("http://12.18.60.199:81"))
using (StreamReader reader = new StreamReader(stream))
{
//stuff
}
}
Keep getting 401 unauthorized, invalid credentials, help!
If I substitute the above address with http://google.com, it'll work, so the code works... username and password have been tested to work in broswer
If you are connecting through a proxy server try adding in your proxy and pass the credentials. For example:
// Prepare web request...
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create("http://www.test.com");
// proxy details
myRequest.Proxy = new WebProxy("http://10.0.0.1", true);
myRequest.Proxy.Credentials = new NetworkCredential("test", "password", "domain");
I had same issue, and found workaround to add Authorization request header. I've used fiddler to get that base64. Never found proper solution, as you all know temp solutions are long-lasting in out world :)
service.Url = "http://127.0.0.1/";
service.SetRequestHeader("Authorization", "Basic dW8sX3NvYXB6SjRma2pzdXZqNDg5ZA==");
service.PreAuthenticate = true;
The following is being tested on Windows 8 and 7.
I have this code, which works when not behind a proxy:
var client = new WebClient();
client.Credentials = new NetworkCredential(USER, PASS);
client.DownloadFile("http://mydns/subfolder/myfile.zip")
The client USER and PASS is a local user on the server.
When I combine that with a proxy, I keep getting the 401 error:
var proxy = WebRequest.DefaultWebProxy;
proxy.Credentials = CredentialCache.DefaultCredentials;
client.Proxy = proxy;
The client has the correct proxy configured, because with the browser I can go to the wanted url.
I also tried with manually setting the proxy Credentials, but that also didn't work:
WebProxy proxy;
if(_proxySetting.Port != null)
proxy = new WebProxy(_proxySetting.Server, _proxySetting.Port);
else
proxy = new WebProxy(_proxySetting.Server);
if(!string.IsNullOrEmpty(_proxySetting.Username))
{
proxy.Credentials = new NetworkCredential(_proxySetting.Username, _proxySetting.Password);
}
client.Proxy = proxy;
I've tried what is explained on the following pages, without any luck:
WebClient generates (401) Unauthorized error
C# webclient and proxy server
http://www.vbforums.com/showthread.php?517076-RESOLVED-2005-WebClient-Credentials-allways-getting-401!
Any help is much appreciated since I'm totally out of ideas.
I have a problem when I do an httprequest and the remote server responds with a redirect and some additional query parameters. The problem is that the additional parameters is empty on certain enviroments.
When I run the code in a test-environment the parameters is not empty.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
WebProxy myProxy = new WebProxy();
Uri newUri = new Uri(ConfigurationManager.AppSettings["proxyUrl"]);
myProxy.Address = newUri;
request.Proxy = myProxy;
request.Timeout = Int32.Parse(ConfigurationManager.AppSettings["PBVtimeout"]);
request.AllowAutoRedirect = true;
request.MaximumAutomaticRedirections = 2;
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(myCertificateValidation);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
log.Debug("PathAndQuery: " + response.ResponseUri.PathAndQuery);
log.Debug("Statuscode: " + response.StatusCode);
log.Debug("Statusdescription: " + response.StatusDescription);
Uri uri = response.ResponseUri;
NameValueCollection qscol = ParseQueryString(uri.Query);
return qscol["Status"] + qscol["Status_code"];
I log StatusCode, StatusDescription and the PathAndQuery of the response. StatusCode and StatusDescription is "OK" in both enviroments but the PathAndQuery looks like this:
Faulty environment: localhost/Service
Correct environment: localhost/Service?Merchant_id=1345&Version=2&Customer_refno=269932&Status=E&Status_code=48
As you can see the faulty enviroments is missing the parameters.
My initial thought was that it was a problem with a firewall "cleaning" the redirect response. But when I did the http request in an ordninary web browser it worked fine.
The code is in C# .Net 2.0 and it runs on a Windows 2003 server.
Any ideas where the problem could be?