"Unauthorized" - While making a call to SOAP api C# - c#

While using the below code to make a call to the SOAP, I am getting the "Unauthorized" as a response.
NetworkCredential credentials = new NetworkCredential("username", "password");
var request = (HttpWebRequest)WebRequest.Create(url);
request.Credentials = credentials;
try
{
WebResponse response = request.GetResponse();
using(Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch(WebException Ex)
{
WebResponse errorResponse = Ex.Response;
using(Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
string errorText = reader.ReadToEnd();
}
throw;
}
Can you please correct me where I am wrong?
I am getting the error :- "The remote server returned an error: (401) Unauthorized."

This should work
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
string authInfo = "username" + ":" + "Password";
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers[HttpRequestHeader.Authorization] = "Basic " + authInfo;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
using (var responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}

This is not an error. It is a warning about your credential. You should send legal user credential to get a response to your end-point. Please check-out this;
NetworkCredential credentials = new NetworkCredential{
Username=//fill your username,
Password=//fill your password but be carefull, is it hashed or not?
};
var request = (HttpWebRequest)WebRequest.Create(url);
request.Credentials = credentials;
try
{
WebResponse response = request.GetResponse();
using(Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch(WebException Ex)
{
WebResponse errorResponse = Ex.Response;
using(Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
string errorText = reader.ReadToEnd();
}
throw;
}

Related

C# REST API Authenticate with Bearer Token

Trying to write a tool which downloads a .zip file from a server via REST API.
It works without any problems with SOAP-UI but my tool doesn't want to download any files.
Always getting this error:
Cannot send a content-body with this verb-type.
My POST-Requests work fine but GET-Requests make problems. I Think there is a problem with my Webrequest-Header.
The authentication has to look like this:
Bearer "Access Token"
Here is my code:
class RestProvider
{
protected string method;
protected string endpoint;
protected string resource;
protected string parameters;
public RestProvider(string method, string endpoint, string resource, string parameters)
{
this.method = method;
this.endpoint = endpoint;
this.resource = resource;
this.parameters = parameters;
}
public string GetResponse()
{
string resultString = string.Empty;
ASCIIEncoding enc = new ASCIIEncoding();
byte[] paramData = enc.GetBytes(parameters);
if (this.method == "post")
{
try
{
WebRequest request = WebRequest.Create(this.endpoint + this.resource);
request.Method = this.method;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = paramData.Length;
Stream stream = request.GetRequestStream();
stream.Write(paramData, 0, paramData.Length);
stream.Close();
WebResponse response = request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
resultString = sr.ReadToEnd();
sr.Close();
stream.Close();
}
catch(Exception ex)
{
resultString = "{\"errorMessages\":[\"" + ex.Message.ToString() + "\"],\"errors\":{}}";
}
}
else if(this.method == "get")
{
try
{
WebRequest request = WebRequest.Create(this.endpoint + this.resource);
request.Headers["Authorization"] = "Bearer " + Convert.ToBase64String(Encoding.Default.GetBytes(this.parameters));
request.Method = this.method;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = paramData.Length;
Stream stream = request.GetRequestStream();
stream.Write(paramData, 0, paramData.Length);
stream.Close();
WebResponse response = request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
resultString = sr.ReadToEnd();
sr.Close();
stream.Close();
}
catch (Exception ex)
{
resultString = "{\"errorMessages\":[\"" + ex.Message.ToString() + "\"],\"errors\":{}}";
}
}
return resultString;
}
}
Any ideas?

Web Service dynamically using HttpWebRequest Unsupported Media Type

public void processVoucher()
{
try
{
string url = "http://192.168.xxx.xx:xxxx/context-root-xxxxxxxx/AccountsPayableManagerPort?WSDL/processVoucher";
StreamReader str = new StreamReader(#"F:\IntelliChief integration to JD Edwards for AP Invoice entry\processVoucher_input_payload.xml");
string ipParameter = str.ReadToEnd();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.ContentType = "application/xml";
req.KeepAlive = true;
req.Timeout = 30000;
req.Accept = "application/xml";//"text/xml";
req.Headers.Clear();
req.Method = "POST";
Encoding encode = Encoding.GetEncoding("utf-8");
using (Stream stm = req.GetRequestStream())
{
using (StreamWriter stmw = new StreamWriter(stm))
{
stmw.Write(ipParameter);
}
}
var response = req.GetResponse(); // here i am getting Unsupported Media Type issue
Stream responseStream = response.GetResponseStream();
StreamReader strReader = new StreamReader(responseStream, encode, true);
string result = strReader.ReadToEnd();
}
catch (Exception ex)
{
MessageBox.Show("Error Message:" + ex.Message);
throw;
}
}
I got requirement of consuming web service, display the result, i am trying to consume web service by using HttpWebRequest class. I running exception in req.GetResponse() any help is appreciated.
public void processVoucher()
{
string soap = null;
try
{
StreamReader str = new StreamReader(#"F:\xxx\some.xml");
soap = str.ReadToEnd();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://192.168.xxx.xx:xxxx/bla-bla-bla/AccountsPayableManagerPort?WSDL");
req.ContentType = "text/xml;charset=\"UTF-8\"";
req.Accept = "text/xml";
req.Method = "POST";
using (Stream stm = req.GetRequestStream())
{
using (StreamWriter stmw = new StreamWriter(stm))
{
stmw.Write(soap);
}
}
using (WebResponse response = req.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
string soapResult = rd.ReadToEnd();
}
}
}
catch (Exception)
{
throw;
}
}
Finally i found solution to the issue, above is the working code. After i changed req.ContentType = "application/xml"; to req.ContentType = "text/xml;charset=\"UTF-8\""; , req.Accept = "application/xml"; to req.Accept = "text/xml"; and i removed req.Headers.Clear(); my code started working thanks all for your support...

HttpWebRequest - payload error

HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(url);
Request.Headers.Add("Authorization", "OAuth " + GetAccessTokenBeta());
Request.Proxy.Credentials = CredentialCache.DefaultCredentials;
Request.Method = "POST";
Request.ContentType = "application/xml";
using (var streamWriter = new StreamWriter(Request.GetRequestStream()))
{
string xml = getXml(tabletype, values.ToArray());
streamWriter.Write(xml);
streamWriter.Flush();
streamWriter.Close();
}
try
{
using (WebResponse response = Request.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
}
}
}
catch (WebException ex)
{
var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Core.ShowError("Error connecting to the webservice." + "\r\n" + resp);
}
I have confirmed that the endpoint and XML work using Postman, but I am running into this issue in C#.
Error sending HTTP request. Message payload is of type: BufferInputStream

The magic number in GZip header is not correct. Make sure you are passing in a GZip stream getting this error

i am working on asp.net webform to passing json string on a url for authenticate but getting error in Gzip.
here is my method to post data
private static string GetResponse(string requestData, string url)
{
string responseXML = string.Empty;
try
{
byte[] data = Encoding.UTF8.GetBytes(requestData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("Accept-Encoding", "gzip");
Stream dataStream = request.GetRequestStream();
dataStream.Write(data, 0, data.Length);
dataStream.Close();
WebResponse webResponse = request.GetResponse();
var rsp = webResponse.GetResponseStream();
if (rsp == null)
{
//throw exception
}
using (StreamReader readStream = new StreamReader(new GZipStream(rsp, CompressionMode.Decompress)))
{
responseXML = JsonConvert.DeserializeXmlNode(readStream.ReadToEnd()).InnerXml;
}
}
catch (WebException webEx)
{
//get the response stream
WebResponse response = webEx.Response;
Stream stream = response.GetResponseStream();
String responseMessage = new StreamReader(stream).ReadToEnd();
}
finally
{
}
return responseXML.ToString();
}
getting this error while i am passing the json object and url
enter image description here

Json POST request to the server but server respond (400) Bad Request

I want to use google api for creation of gmail user account. I am sending JSON request to server for getting authorization code but I got these error in httpwebresponse :-
Exception Details: System.Net.WebException: The remote server returned an error: (400) Bad Request
var request = (HttpWebRequest)WebRequest.Create(#"https://accounts.google.com/o/oauth2/auth");
request.Method = "POST";
request.ContentType = "text/json";
request.KeepAlive = false;
//request.ContentLength = 0;
using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = "{\"scope\":\"https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile\"," + "\"state\":\"%2Fprofile\"," + "\"redirect_uri\":\"http://gmailcheck.com/response.aspx\"," + "\"response_type\":\"code\"," + "\"client_id\":\"841994137170.apps.googleusercontent.com\"}";
streamWriter.Write(json);
// streamWriter.Flush();
//streamWriter.Close();
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
StreamReader responsereader = new StreamReader(response.GetResponseStream());
var responsedata = responsereader.ReadToEnd();
//Session["responseinfo"] = responsereader;
//testdiv.InnerHtml = responsedata;
}
}
As soon as you get an exception, you have to read the actual responce from server there should be something helpfull. Like an error description or extended status code...
For Instance:
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
... your code goes here....
}
catch (WebException ex)
{
using (WebResponse response = ex.Response)
{
var httpResponse = (HttpWebResponse)response;
using (Stream data = response.GetResponseStream())
{
StreamReader sr = new StreamReader(data);
throw new Exception(sr.ReadToEnd());
}
}
}

Categories

Resources