My code is sending a HTTP POST request with a JSON body. It is working
as expected in localhost but when I deploy it on server then it is
working differently. On my local machine response is okey but on server the response says request is not same !
var request = WebRequest.Create($"{baseUrl}{resourceAddress}");
request.Method = "POST";
request.ContentType = "application/json";
var json = JsonConvert.SerializeObject(requestBody);
request.ContentLength = json.Length;
using (var webStream = request.GetRequestStream())
{
using (var requestWriter = new StreamWriter(webStream, Encoding.ASCII))
{
requestWriter.Write(json);
}
}
try
{
var webResponse = request.GetResponse();
using var webStream = webResponse.GetResponseStream() ?? Stream.Null;
using var responseReader = new StreamReader(webStream);
var response = responseReader.ReadToEnd();
var paymentUrlResponse = JsonConvert.DeserializeObject<PaymentUrlResponse>(response);
if(paymentUrlResponse.Result.ResultCode != "00")
{
throw new Exception("Failed to get URL. Http Response: OK , Result Code: " + paymentUrlResponse.Result.ResultCode);
}
_httpContextAccessor.HttpContext.Response.Redirect(redirectionUrl);
}
Related
I'm trying to log in into iCloud using a Json Post request in C#. Before trying to implement the code I was studying a little bit the iCloud requests using Chrome Console and using an Ad-on to replicate the requests in order to obtain the same result of the website.
First of All I checked the request directly from iCloud website:
And this is the response:
{
"serviceErrors" : [ {
"code" : "-20101",
"message" : "Il tuo IDĀ Apple o la password non sono corretti."
} ]
}
Using "Advance REST Client" ad Chrome plugin to replicate the request I ve tried the same Json request to the same Url. But I get Empty response:
I Also tried to copy and paste the whole Header (All the settings) and than send the request but the response is the same:
Anyone has an Advice?
UPDATE: I tried to implement A Json request through c# program:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://idmsa.apple.com/appleauth/auth/signin");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{accountName: \"briesanji #gmail.com\", password: \"testPassword\", rememberMe: false, trustTokens: []}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
The problem is that Execution breaks when the
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
is hit and it gives me this error: System.Net.WebException: 'Error Remote Server: (400) Request not valid.'
UPDATE: I solved in this way:
void POST(string url, string jsonContent)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(jsonContent);
request.ContentLength = byteArray.Length;
request.ContentType = #"application/json";
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
length = response.ContentLength;
}
}
catch (WebException ex)
{
// Log exception and throw as for GET example above
}
}
string GET(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
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();
// log errorText
}
throw;
}
}
Anyways I tested also the Answer and it was good to.. So I check it as valid thanks.
With this i dont get any error and the response content of the second request just tells me that there were too many failed logins for the test account...
private static void ICloud()
{
var cc = new CookieContainer();
var first = (HttpWebRequest)WebRequest.Create("https://idmsa.apple.com/appleauth/auth/signin?widgetKey=83545bf919730e51dbfba24e7e8a78d2&locale=de_DE&font=sf");
first.Method = "GET";
first.CookieContainer = cc;
var response1 = (HttpWebResponse)first.GetResponse();
using (var streamReader = new StreamReader(response1.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
var second = (HttpWebRequest)WebRequest.Create("https://idmsa.apple.com/appleauth/auth/signin");
second.ContentType = "application/json";
second.Method = "POST";
second.Accept = "application/json";
second.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
second.Referrer = "https://idmsa.apple.com/appleauth/auth/signin?widgetKey=83545bf919730e51dbfba24e7e8a78d2&locale=de_DE&font=sf";
second.Headers.Add("X-Requested-With", "XMLHttpRequest");
second.Headers.Add("X-Apple-Widget-Key", "83545bf919730e51dbfba24e7e8a78d2");
using (var streamWriter = new StreamWriter(second.GetRequestStream()))
{
string json = "{\"accountName\":\"test#icloud.com\",\"password\":\"test\",\"rememberMe\":false,\"trustTokens\":[]}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
try
{
var response2 = (HttpWebResponse)second.GetResponse();
using (var streamReader = new StreamReader(response2.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
catch(WebException we)
{
using (var r = new StreamReader(we.Response.GetResponseStream()))
{
var result2 = r.ReadToEnd();
}
}
}
I have managed to successfully read my Facebook account by using the following code:
IAuthorizationState authorization = client.ProcessUserAuthorization();
if (authorization == null)
{
// Kick off authorization request
client.RequestUserAuthorization();
}
else
{
var request = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString(authorization.AccessToken));
Session["access_token"] = authorization.AccessToken;
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var graph = FacebookGraph.Deserialize(responseStream);
this.nameLabel.Text = HttpUtility.HtmlEncode(graph.Name);
}
}
}
I am now trying to POST to my Facebook news feed and I am struggling to find a guide to help me through it. I have tried to start it myself and for some reason it seems to throw back a 400: Bad Request error.
var request = WebRequest.Create("https://graph.facebook.com/me/feed?");
var postdata = "message=hello";
postdata += "&access_token" + Session["access_token"].ToString();
var data = Encoding.ASCII.GetBytes(postdata);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
Can anyone help me understand why my code is returning the error?
Use http://facebooksdk.net/ to make your job simple. Store access token and reuse for every request till it gets expired.
I'm trying to convert curl request to WebRequest in C# but not able to get the response as it always returns 401 unauthorized error
Here is the working curl request:
curl -k -v https://api.demo.peertransfer.com/v1/transfers -H "Content-Type: application/json" -X POST -d "{\"provider\":\"HUL\",\"payment_destination\":\"hult-applicationfee\",\"amount\":\"29000\",\"callback_url\":\"http://studentapplication.local/en/nextsteps\",\"callback_id\":\"abc1234546asas\",\"dynamic_fields\":{\"student_id\":\"32453245\",\"student_first_name\":\"Candy\",\"student_last_name\":\"Student\"}}" -H "X-Peertransfer-Digest: zYUt+Pn0A06wsSbCrrbAZn68Aslq9CbSUAKBrUEwIzI="
Output:
The result in the red box is what I need to get in WebRequest Response,
here is my C# code
private void testnewfunc()
{
string value = "{\"provider\":\"HUL\",\"payment_destination\":\"hult-applicationfee\",\"amount\":\"29000\",\"callback_url\":\"http://studentapplication.local/en/nextsteps\",\"callback_id\":\"abc1234546asas\",\"dynamic_fields\":{\"student_id\":\"32453245\",\"student_first_name\":\"Candy\",\"student_last_name\":\"Student\"}}";
var URI = new Uri("https://api.demo.peertransfer.com/v1/transfers");
byte[] data = System.Text.ASCIIEncoding.Default.GetBytes(value);
var requst = (HttpWebRequest)WebRequest.Create(URI);
requst.UserAgent = "curl/7.43.0";
requst.Method = "POST";
requst.KeepAlive = true;
requst.AllowAutoRedirect = true;
requst.ContentType = " application/json";
requst.ContentLength = data.Length;
// wc.Headers["Content-Type"] = "application/json";
requst.Accept = "*/*";
//Or any other encoding type.
string result = System.Convert.ToBase64String(data);
var uname = "hultdemo2015";
var pword = "gEejgC0GF8pCbI7C";
var creds = string.Format("{0}:{1}", uname, pword);
creds = Convert.ToBase64String(Encoding.ASCII.GetBytes(creds));
requst.Headers["Authorization"] = string.Format("{0} {1}", "Basic", creds);
requst.Headers["X-Peertransfer-Digest"] = string.Format("{0}", "zYUt+Pn0A06wsSbCrrbAZn68Aslq9CbSUAKBrUEwIzI=");
using (Stream stream = requst.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var httpResponse = (HttpWebResponse)requst.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
//Now you have your response.
//or false depending on information in the response
// return true;
}
}
Not sure what I'm making wrong in the WebRequest.
Here's my solution:
var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false });
var message = new HttpRequestMessage(HttpMethod.Post, new Uri("https://api.demo.peertransfer.com/v1/transfers"));
message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
message.Headers.Add("X-Peertransfer-Digest", "zYUt+Pn0A06wsSbCrrbAZn68Aslq9CbSUAKBrUEwIzI=");
message.Content = new StringContent("{\"provider\":\"HUL\",\"payment_destination\":\"hult-applicationfee\",\"amount\":\"29000\",\"callback_url\":\"http://studentapplication.local/en/nextsteps\",\"callback_id\":\"abc1234546asas\",\"dynamic_fields\":{\"student_id\":\"32453245\",\"student_first_name\":\"Candy\",\"student_last_name\":\"Student\"}}", Encoding.UTF8, "application/json");
var responseMessage = await client.SendAsync(message);
MessageBox.Show(string.Format("Status Code: {0}{1}Content-Type: {2}{1}Date: {3}{1}Location:{4}", responseMessage.StatusCode, Environment.NewLine, responseMessage.Content.Headers.ContentType, responseMessage.Headers.Date, responseMessage.Headers.Location));
And here's the response from the server (same as curl):
Version compatible with .Net 4.0
var data = "{\"provider\":\"HUL\",\"payment_destination\":\"hult-applicationfee\",\"amount\":\"29000\",\"callback_url\":\"http://studentapplication.local/en/nextsteps\",\"callback_id\":\"abc1234546asas\",\"dynamic_fields\":{\"student_id\":\"32453245\",\"student_first_name\":\"Candy\",\"student_last_name\":\"Student\"}}";
var request = (HttpWebRequest)WebRequest.Create(new Uri("https://api.demo.peertransfer.com/v1/transfers"));
request.Method = "POST";
request.AllowAutoRedirect = false;
request.Accept = "*/*";
request.Headers.Add("X-Peertransfer-Digest", "zYUt+Pn0A06wsSbCrrbAZn68Aslq9CbSUAKBrUEwIzI=");
request.ContentType = "application/json";
request.ContentLength = data.Length;
using (var reqStream = request.GetRequestStream())
using (var writer = new StreamWriter(reqStream))
{
writer.Write(data);
}
var response = request.GetResponse();
MessageBox.Show(response.Headers.ToString());
Make sure you include these using statements:
using System.IO;
using System.Net;
and these are the response headers from the server:
curl https://api.stripe.com/v1/charges
\ -u sk_test_BQokikJOvB432343iI2HlWgH4olfQ2:
\ -d amount=400
\ -d currency=usd
\ -d card=tok_15CVG02eZvKYlo2CDVUHUs56
I'm new to curl and need to convert the above curl request into an ASP.NET web request. I believe the -d are post parameters, but I am unsure how to pass in the -u and what -u stands for. Below is the code I have so far. FYI this is for the Stripe Payment Gateway, I can't use the ASP.NET Library because I can add any dlls to the solution I am running so I am using their CURL API.
string formencodeddata = "amount=400¤cy=usd&card=tok_15CVG02eZvKYlo2CDVUHUs56";
byte[] formbytes = System.Text.ASCIIEncoding.Default.GetBytes(formencodeddata);
//Create a new HTTP request object, set the method to POST and write the POST data to it
var webrequest = (HttpWebRequest)WebRequest.CreateHttp("https://api.stripe.com/v1/charges");
webrequest.Method = "POST";
webrequest.ContentType = "application/x-www-form-urlencoded";
using (Stream postStream = webrequest.GetRequestStream()) {
postStream.Write(formbytes, 0, formbytes.Length);
}
//Make the request, get a response and pull the data out of the response stream
var webresponse = (HttpWebResponse)webrequest.GetResponse();
Stream responseStream = webresponse.GetResponseStream();
var reader = new StreamReader(responseStream);
string result = reader.ReadToEnd();
This was my final solution:
var postUrl = new StringBuilder();
postUrl.Append("card=");
postUrl.Append(token);
postUrl.Append("currency=usd");
postUrl.Append("&x_amount=");
postUrl.Append(transactionAmount.ToString());
byte[] formbytes = System.Text.ASCIIEncoding.Default.GetBytes(postUrl.ToString());
//Create a new HTTP request object, set the method to POST and write the POST data to it
var webrequest = (HttpWebRequest)WebRequest.Create(Url);
webrequest.Method = "POST";
webrequest.UserAgent = "Stripe Payment Processor";
webrequest.ContentType = "application/x-www-form-urlencoded";
webrequest.Headers.Add("Stripe-Version", "2014-12-22");
webrequest.Headers.Add("Authorization", String.Concat("Basic ", (Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:", this.PrivateKey))))));
using (Stream postStream = webrequest.GetRequestStream())
{
postStream.Write(formbytes, 0, formbytes.Length);
}
//Make the request, get a response and pull the data out of the response stream
StreamReader reader = null;
string stripeResponse;
try
{
HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
Stream responseStream = webresponse.GetResponseStream();
reader = new StreamReader(responseStream);
stripeResponse = reader.ReadToEnd();
}
catch (WebException exception)
{
using (WebResponse response = exception.Response)
{
using (Stream data = response.GetResponseStream())
using (reader = new StreamReader(data))
{
stripeResponse = reader.ReadToEnd();
}
}
}
I am working with GoogleApi. I want to get accesstoken as response using Google api. when I am sending httpwebrequest for getting access token then
When I used :- request.Method = "POST"
Exception:- HTTP method POST is not supported by this URL
When I used :- request.Method = "GET"
Exception:- System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type
The actual request might look like:
POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded
code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=8819981768.apps.googleusercontent.com&
client_secret={client_secret}&
redirect_uri=https://oauth2-login-demo.appspot.com/code&
grant_type=authorization_code
A successful response is returned as a JSON array, similar to the following:
{
"access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
"expires_in":3920,
"token_type":"Bearer"
}
My Code is :-
var request = (HttpWebRequest)WebRequest.Create(#"https://accounts.google.com");
request.Method = "POST";
request.ContentType = "application/json";
//request.KeepAlive = false;
// request.Headers[HttpRequestHeader.Authorization] = "";
//request.ContentLength = 0;
using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = "{\"code\":\"4/M1IIC8htCuvYORuVJK16oadDb3Gd.cigIKgaPjvUYXE-sT2ZLcbSrckCLgwI\"," + "\"client_id\":\"841994137170.apps.googleusercontent.com\"," + "\"client_secret\":\"MXjKvevD_cKp5eQWZ1RFXfdo\"," + "\"redirect_uri\":\"http://gmailcheck.com/response.aspx\"," + "\"grant_type\":\"authorization_code\"}";
streamWriter.Write(json);
// streamWriter.Flush();
//streamWriter.Close();
}
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
StreamReader responsereader = new StreamReader(response.GetResponseStream());
var responsedata = responsereader.ReadToEnd();
//Session["responseinfo"] = responsereader;
}
}
catch (WebException ex)
{
using (WebResponse response = ex.Response)
{
var httpResponse = (HttpWebResponse)response;
using (Stream data = response.GetResponseStream())
{
var sr = new StreamReader(data);
throw new Exception(sr.ReadToEnd());
}
}
}
This is the problem:
var request = (HttpWebRequest)WebRequest.Create(#"https://accounts.google.com");
That's not the URL you showed originally. That's just the domain root. You need:
var request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
I've removed the # as your string doesn't include any line breaks or backslashes, so there's no benefit in using a verbatim string literal.
(Additionally, I'd expect this to be covered in the Google Client APIs - is it not?)