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";
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();
response = requests.patch( "https://<manageraddress>/api/admin/configuration/v1/conference/1/", auth=('<user1>', '<password1>'), verify=False, data=json.dumps({'pin': '1234'}) https://tsmgr.tsecurevideo.com/api/admin/configuration/v1/conference/1/"
I have tried
HttpWebRequest httpWReq =(HttpWebRequest)WebRequest.Create(string.Format("https://tsmgr.tsecurevideo.com/api/admin/configuration/v1/conference/2/"));
Encoding encoding = new UTF8Encoding();
string postData = "{\"pin\":\"1234\"}";
byte[] data = encoding.GetBytes(postData);
httpWReq.ProtocolVersion = HttpVersion.Version11;
httpWReq.Method = "POST";
httpWReq.ContentType = "application/json";//charset=UTF-8";
string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("admin" + ":" + "password"));
httpWReq.Headers.Add("Authorization", "Basic " + credentials);
httpWReq.ContentLength = data.Length;
Stream stream = httpWReq.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
string s = response.ToString();
StreamReader reader = new StreamReader(response.GetResponseStream());
I am getting the error
The remote server returned an error: (501) Not Implemented.
try to send credentials in this way
string auth = string.Format("{0}:{1}", "admin","password");
string data = Convert.ToBase64String(Encoding.ASCII.GetBytes(auth));
string credentials= string.Format("{0} {1}", "Basic", data );
httpWReq.Headers[HttpRequestHeader.Authorization] = credentials;
refer here for documentation in Encoding.ASCII
From the HTTP spec:
501 Not Implemented
The server does not support the functionality required to fulfill the request. This is the appropriate response when the server does not recognize the request method and is not capable of supporting it for any resource.
Sounds like the server doesn't support the PATCH method.
I trying to use Google GCM for sending push notifications. But get a WebException that says that the remote server returns 401 unautorized. I can't foung why it doen't work.
Anyone that knows why it doesn't work?
Here is my code:
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
Request.Method = "POST";
Request.KeepAlive = false;
string postData = "{ 'registration_ids': [ '"+registrationId+"' ], 'data': {'message': '"+message+"'}}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
Request.ContentType = "application/json";
//Request.ContentLength = byteArray.Length;
//Request.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + AuthString);
Request.Headers.Add(HttpRequestHeader.Authorization, "Authorization: key=AIzaSyCEygavdzrNM3pWNPtvaJXpvW66CKnjH_Y");
//-- Delegate Modeling to Validate Server Certificate --//
//-- Create Stream to Write Byte Array --//
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
//-- Post a Message --//
WebResponse Response = Request.GetResponse();
HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
{
var text = "Unauthorized - need new token";
}
else if (!ResponseCode.Equals(HttpStatusCode.OK))
{
var text = "Response from web service isn't OK";
}
StreamReader Reader = new StreamReader(Response.GetResponseStream());
string responseLine = Reader.ReadLine();
Reader.Close();
Daniel - Dude there is an issue with the GCM documentation ! Use Browser key as the authorization key at the place of Server API key . It will work.
OK, i am just shooting in the dark here. Take a look at this line:
Request.Headers.Add(HttpRequestHeader.Authorization, "Authorization: key=AIzaSyCEygavdzrNM3pWNPtvaJXpvW66CKnjH_Y");
Shouldn't it be:
Request.Headers.Add(HttpRequestHeader.Authorization, "key=AIzaSyCEygavdzrNM3pWNPtvaJXpvW66CKnjH_Y");
Since you're telling it this is a Authorization header, there's no need to add 'Authorization: ' again, does it?
Also, make sure the string constant 'HttpRequestHeader.Authorization' is 'Authorization'.
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);
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.