I am trying to post a XML to REST Service. Here's the code I am using:
I am getting following error, while calling the service.
The remote server returned an error: (401) Unauthorized.
I have also tried setting NetworkCredentials directly i.e.
NetworkCredential nc = new NetworkCredential(username, password);
serviceRequest.Credentials = nc;
Thanks for your help.
Uri address = new Uri("https://localhost:30000/restservice/");
// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
// Set type to POST
request.Method = "POST";
request.ContentType = "application/json";
string data = #"<Sample XML Here>";
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);
// Set the content length in the request headers
request.ContentLength = byteData.Length;
// Write data
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
string usernamePassword = username + ":" + password;
CredentialCache mycache = new CredentialCache();
mycache.Add(address, "Basic", new NetworkCredential(username, password));
request.Credentials = mycache;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
Response.Write(reader.ReadToEnd());
}
Use Fiddler and look in the WWW-Authenticate header that is returned from the server. That will tell you what kind of authentication scheme the server supports.
Couple of things to try:
Change the content type as you're not posting json to it
Not encode the data as its expecting xml, not a binary stream
Hope this helps.
try set Credentials in request like this
request.Credentials = new NetworkCredential(username, password);
Related
I am using .net to connect to PayPal to get access token. I was following the documentary provided on PayPal. https://developer.paypal.com/docs/api/overview/#make-your-first-call
This is what I have so far. Mostly go it from here. Although it connects, it does not return anything back. I tried it on the Postman and I am getting a json object with access token, but nothing is returned here.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.sandbox.paypal.com/v1/oauth2/token");
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(clientId + ":" + clientSecret));
request.Accept = "application/json";
request.Headers.Add("Accept-Language", "en_US");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 10000;
byte[] postBytes = Encoding.ASCII.GetBytes("grant_type=client_credentials");
Stream postStream = request.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Flush();
postStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
This is what I am getting from on breakpoints.
response.CharacterSet = ""
response.ContentLength = 899
response.StatusCode = OK
Found the answer. The following code provides the json object.
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
Console.WriteLine(responseString); // This will display the answer as JSON, now just parse it.
Follow PayPal's .NET SDK Quick Start guide. You can authenticate and get your access token as follows:
using PayPal.Api;
// Authenticate with PayPal
var config = ConfigManager.Instance.GetProperties();
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
In my web project, I am using http request and response for access https payment site. But when I call getresponse() function, it return "Precondition failed (412)" error.
HttpWebRequest paymentRequest = (HttpWebRequest)WebRequest.Create("https://xxxxxx/authorize");
Uri uri = new Uri("https://xxxxxx/authorize");
NetworkCredential netCredential = new NetworkCredential("XXXXXXXXX", "XXXXXXXXX");
paymentRequest.Credentials = netCredential.GetCredential(uri, "Basic");
paymentRequest.PreAuthenticate = true;
byte[] Data = System.Text.Encoding.ASCII.GetBytes(sXMLTemplate);
paymentRequest.Method = "POST";
paymentRequest.Headers.Add("MIME-Version", "1.0");
paymentRequest.Headers.Add("Request-number", "1");
paymentRequest.Headers.Add("Document-type", "Request");
paymentRequest.Headers.Add("Content-transfer-encoding", "application/xml");
paymentRequest.ContentType = "application/xml";
paymentRequest.ContentLength = Data.Length;
paymentRequest.KeepAlive = true;
Stream streamWriter = paymentRequest.GetRequestStream();
streamWriter.Write(Data, 0, Data.Length);
streamWriter.Close();
HttpWebResponse paymentResponse = (HttpWebResponse)paymentRequest.GetResponse();
Stream responseStream = paymentResponse.GetResponseStream();
reader = new XmlTextReader(responseStream);
How to fix this error?
Please check if XML data you are POSTing validates successfully and there is no missing XML elements if XML schema is enforced
Have a look at the valid content-transfer-encodings.
BASE64
8BIT
7BIT
BINARY
QUOTED-PRINTABLE
application/something is for Content-Type, not encoding.
For more info, look at the specs here:
http://www.w3.org/Protocols/rfc1341/5_Content-Transfer-Encoding.html
What I do Think you're after is this:
paymentRequest.Headers.Add("Content-type", "application/xml");
or simply:
paymentRequest.ContentType = "application/xml";
I want to send a cookie pulled from Google Chromes network F12 tab to preproduce hitting the UI in an HTTP Request instead. However, I need to send the cookie that goes with the request. I can't seem to attach the cookie string to the request.
Capture from Google Chrome (f12)
http://imgur.com/8wEaSSC.png
I need to attach that cookie to the request when I send it out.
string cookie = "JSESSIONID_loginLite_remote=LJyKVLHGLZrpTq3npBWh8CJyqTND32HpscL48ndnSp0hj2g6yhcK!.....";
string info = "RemoteObjectTimestamp=1430842283795&RemoteObjectRequest=%7B%22destination%22%...";
char[] arr = info.ToCharArray();
byte[] data = System.Text.Encoding.ASCII.GetBytes(arr);
HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(URL);
myHttpWebRequest.Method = "POST";
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
myHttpWebRequest.ContentLength = data.Length;
//Data to write is not empty
if (data.Length > 0)
{
Stream requestStream = myHttpWebRequest.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
}
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
Stream responseStream = myHttpWebResponse.GetResponseStream();
StreamReader myStreamReader = new StreamReader(responseStream, System.Text.Encoding.Default);
string pageContent = myStreamReader.ReadToEnd();
myStreamReader.Close();
responseStream.Close();
myHttpWebResponse.Close();
Console.WriteLine(pageContent);
Add the lines:
myHttpWebRequest.CookieContainer = new CookieContainer();
myHttpWebRequest.CookieContainer.SetCookies(new Uri("your domain here"), cookie);
Don`t forget replace "your domain here" to domain of target request Uri
I am using a .net webservice to communicate via JSON with an external API (Urban Airship). There is something incorrect in my outbound JSON, and supposedly, along with the 400 Bad Request error I am seeing, they are returning a JSON object to me that has error logging that will help me identify the problem.
Only thing is, I can't figure out how to accept and read the JSON error message... all I get is the 400 Bad Request. Is there a way I can modify my code to see this returned object?
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
req.ContentType = contentType;
req.Method = method;
req.ContentLength = jsonDataBytes.Length;
CredentialCache credentialCache = new CredentialCache();
string username = "x";
string password = y
credentialCache.Add(uri, "Basic", new NetworkCredential(username, password));
req.Credentials = credentialCache;
req.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(username + ":" + password)));
req.Accept = "application/vnd.urbanairship+json; version=3;";
dynamic stream = req.GetRequestStream();
stream.Write(jsonDataBytes, 0, jsonDataBytes.Length);
stream.Close();
dynamic response = req.GetResponse().GetResponseStream();
StreamReader reader = new StreamReader(response);
dynamic res = reader.ReadToEnd();
reader.Close();
response.Close();
I'm trying to get the access token from the windows live connect api by using this code
string requestUrl = "https://consent.live.com/AccessToken.aspx";
// Request the access token.
string postData = string.Format("{0}?wrap_client_id={1}&wrap_client_secret={2}&wrap_callback={3}&wrap_verification_code={4}&idtype={5}",
requestUrl,
"000000004C039809",
"l4VJekL1vFL1iFVmcP5qLkWv9ukY4mdl",
"http://ewshops.com",
"dac5d71d-d640-30d1-ebed-3576b132b3ec",
"cid");
byte[] postDataEncoded = System.Text.Encoding.UTF8.GetBytes(postData);
WebRequest req = HttpWebRequest.Create(requestUrl);
req.Method = "POST";
// req.
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postDataEncoded.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(postDataEncoded, 0, postDataEncoded.Length);
WebResponse res = req.GetResponse();
string responseBody = null;
using (StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8))
{
responseBody = sr.ReadToEnd();
}
// Process FORM POST.
NameValueCollection responseCollection = System.Web.HttpUtility.ParseQueryString(responseBody);
return responseCollection["wrap_access_token"];
but I've recieved the following error
The remote server returned an error: (401) Unauthorized.
Show us the response body, it usually contains more information. You should also urlencode http://ewshops.com before adding it to the uri.
I had the same problem and fixed it as follows. Remove the requestUrl ("https://consent.live.com/AccessToken.aspx") and the subsequent "?" from your postData. The POST data should be in x-www-form-urlencoded format and that does not include the request URL. Also HttpUtility.UrlEncode() all the parameters.