Web Request error 407 Proxy Authentication Required - c#

Trying to GetResponse From a web site;
using System.Text;
using System.Net;
using System.IO;
namespace DutyPharmacy751013
{
class Program
{
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com/");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Encoding encoding = Encoding.GetEncoding(response.CharacterSet);
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream, encoding);
string responseText= reader.ReadToEnd();
}
}
}
This code is working on win7 and LAN
and on win8 and any of wireless connection
but doesn't work on win8 and LAN error: 407 Proxy authentication required.
Is there any solution.
Thanks.

try with adding proxy credentials to request and also give network credentials
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com/");
request.Credentials = new NetworkCredential("username", "pw");
WebProxy webProxy = new WebProxy("http://myproxy.net:8080/", true)
{
Credentials = new NetworkCredential("username", "pw"),
UseDefaultCredentials = false
};
request.Proxy = webProxy;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//rest of the code...
Edit
For requests that you create, you can disable automatic proxy detection at the request level by using a null Proxy with your request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com/");
request.Proxy = null;
//rest of the code

WebProxy webProxy = new WebProxy("http://myproxy.net:8080/", true)
{
UseDefaultCredentials = false,
Credentials = new NetworkCredential("username", "pw")
};
Please note Correct sequence to set property {other wise failed for me}

Related

Unable to call onesignal api within office but working from external wifi

I am using C# to call OneSignal Create Notifications API. Its working from my home but when i try to send it from my office, it gives a 400 BAD REQUEST.
The error that i get is
The error that comes is Please include a case-sensitive header of
Authorization: Basic <YOUR-REST-API-KEY-HERE> with a valid REST API key."],
"reference":["https://documentation.onesignal.com/docs/accounts-and-keys#section-keys-ids"]
Also, in office network, when i send it from OneSignal Dashboard it works.
Is it a firewall issue?
Tested with POSTMAN and got the same results. POSTMAN working outside office network and giving 400 Bad Request inside office network.
using System.IO;
using System.Net;
using System.Text;
var request = WebRequest.Create("https://onesignal.com/api/v1/notifications") as HttpWebRequest;
request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.Headers.Add("authorization", "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjxx");
var serializer = new JavaScriptSerializer();
var obj = new { app_id = "5eb5a37e-b458-11e3-ac11-000c2940e6xx",
contents = new { en = "English Message" },
include_player_ids = new string[] {"all"} };
var param = serializer.Serialize(obj);
byte[] byteArray = Encoding.UTF8.GetBytes(param);
string responseContent = null;
try {
using (var writer = request.GetRequestStream()) {
writer.Write(byteArray, 0, byteArray.Length);
}
using (var response = request.GetResponse() as HttpWebResponse) {
using (var reader = new StreamReader(response.GetResponseStream())) {
responseContent = reader.ReadToEnd();
}
}
}
catch (WebException ex) {
System.Diagnostics.Debug.WriteLine(ex.Message);
System.Diagnostics.Debug.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
}
System.Diagnostics.Debug.WriteLine(responseContent);
try following
System.Net.CredentialCache credentialCache = new System.Net.CredentialCache();
credentialCache.Add(
new System.Uri("http://www.yoururl.com/"),
"Basic",
new System.Net.NetworkCredential("username", "password")
);
...
...
httpWebRequest.Credentials = credentialCache;
but i think you should use test RESTFUL tools to check what parameters can return correct value at all first.
The issue is solved by adding the onesignal host to our firewall as a trusted site.

Cant call method from web service

Why can't I call web service method like that:
ws test = new ws();
test.Credentials = new NetworkCredential("UserName", "Password");
var temp = test.Method(1, "test");`
But this work:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("url");
req.Credentials = new NetworkCredential("UserName", "Password");
using (WebResponse response = req.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string result= reader.ReadToEnd();
}
}
Web service use https.
I get this error:
System.Net.WebException: The request failed with HTTP status 403: Forbidden.

one connection multiple requests Rest Service

How can one issue multiple requests using the same service?
I have created a static httpWebRequest:
private static HttpWebRequest request;
//private static StreamReader streamReader;
//private StreamWriter streamWriter;
public CentralRestService2(LogFile log)
{
if (request == null)
{
request = (HttpWebRequest)WebRequest.Create("service address");
request.Method = "POST";
request.Accept = "*/*";
request.ContentType = "application/json";
request.Headers["Authorization"] = "username and password";
request.KeepAlive = true;
}
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string body = new JavaScriptSerializer().Serialize(emailRequest);
streamWriter.Write(body);
}
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
response.Close();
}
I get error messages including that the stream cannot be written to. The connection has unexpectedly closed. I can't seem to find the answer anywhere!
Don't create static HttpWebRequest.
Request does not represent a connection, but it uses ServicePointManager which manages underlying TCP connections for you.
Just create a new instance of HttpWebRequest every time you need to send a request.
UPDATE:
If you want to create a client for your service, you should use HttpClient instead:
// add reference to System.Net.Http and System.Net.Http.Formatting
using System.Net.Http;
// with a handler you can configure the client and its behavior
var handler = new HttpClientHandler();
var httpClient = new HttpClient(handler);
httpClient.BaseAddress = new Uri("service address");
httpClient.DefaultRequestHeaders.Add("Authorization", "username and password");
var response = await httpClient.PostAsJsonAsync(httpClient.BaseAddress, emailRequest);

C# Siteminder Authentication

I am trying to write some code to connect to an HTTPS site that uses Siteminder authentication.
I keep getting a 401. Any ideas?
I have read a few different things on here but none have really seemed all that helpful. I am also using Fiddler/Firefox Tamper to snoop what's going on.
Here is what I've got so far in regards to code:
try
{
Uri uri = new Uri("https://websiteaddresshere");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri) as HttpWebRequest;
request.Accept = "text/html, application/xhtml+xml, */*";
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko";
// request.Connection = "Keep-Alive";
// request.Method = "Get";
// request.Accept = "text";
request.AllowAutoRedirect = true;
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
Cookie emersoncookie = new Cookie("SMCHALLENGE", "YES");
emersoncookie.Domain = "mydomain";
emersoncookie.Path = "/";
// authentication
var cache = new CredentialCache();
cache.Add(uri, "False", new NetworkCredential("myusername", "mypassword"));
request.Credentials = cache;
// response.
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
XmlTextReader reader = new XmlTextReader(stream);
MessageBox.Show(stream.ToString());
}
}
}
catch (WebException exception)
{
string responseText;
using (var reader = new StreamReader(exception.Response.GetResponseStream()))
{
responseText = reader.ReadToEnd();
MessageBox.Show(responseText.ToString());
}
}
After doing some more reading on the MSDN website I decided to go a different route.
I ended up making this a service since it will need to be a service at the end of the day and did the following:
CookieContainer emersoncookie = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("https://websiteaddress");
request.Credentials = new NetworkCredential("username", "password");
request.CookieContainer = emersoncookie;
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();
Stream resStream = response.GetResponseStream();
using (Stream output = File.OpenWrite(#"c:\\somefolder\\somefile.someextention"))
using (Stream input = resStream)
{
input.CopyTo(output);
}
To anyone that might be running into Siteminder authentication issues, this piece of code works pretty well.
I couldn't get Jasen's code to work. Maybe your SM setup is different from mine. But with SiteMinder it's generally a two step authentication process. The code block below works for me:
//Make initial request
RestClient client = new RestClient("http://theResourceDomain/myApp");
client.CookieContainer = new CookieContainer();
IRestResponse response = client.Get(new RestRequest("someProduct/orders"));
//Now add credentials.
client.Authenticator = new HttpBasicAuthenticator("username", "password");
//Get resource from the SiteMinder URI which will redirect to the correct API URI upon authentication.
response = client.Get(new RestRequest(response.ResponseUri));
Although this uses RestSharp, it can be easily replicated using HttpClient or even HttpWebRequest.

Httpwebrequest not retrieving Cookies

I have created the following code, which as far as Im aware should work fine? It is not receiving any cookies at all, I have double checked with wire shark and the cookies are being returned... this is being developed on Windows Phone 7.
byte[] content = GetLoginRequestContent(username, password);
CookieContainer cookieContainer = new CookieContainer();
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(LoginUri);
httpWebRequest.ContentType = AuthContentType;
httpWebRequest.Method = "POST";
httpWebRequest.Headers["referer"] = LoginRequestReferer;
httpWebRequest.CookieContainer = cookieContainer;
httpWebRequest.Headers[HttpRequestHeader.ContentLength] = content.Length.ToString();
httpWebRequest.BeginGetRequestStream(async1 =>
{
using (Stream stream = httpWebRequest.EndGetRequestStream(async1))
stream.Write(content, 0, content.Length);
httpWebRequest.BeginGetResponse(async2 =>
{
HttpWebResponse rep = (HttpWebResponse)httpWebRequest.EndGetResponse(async2);
CookieCollection cookies = rep.Cookies;
using (Stream stream = rep.GetResponseStream())
using (StreamReader sr = new StreamReader(stream))
{
String contentX = sr.ReadToEnd();
//if blah blah
}
}, null);
}, null);
If the cookie is marked with HttpOnly (which is often the case with session cookies) you cannot access them it client side scripting for security reasons. It is sent to the client, the client resends it to the server (if it posses a cookie container) on subsequent requests, but you cannot read its value on the client.

Categories