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:
Related
I need to do this from C #, it's a post that works ok from the web, but I don't know what I'm doing wrong.
I leave a picture of the F12 when I act on the web, I try to do the same in C # but I can't get it to work.
WebRequest request = WebRequest.Create("https://xxxxxxxxxxxxx");
var Token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
request.Headers.Add("accessToken", Token);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
var data = "lockId=xxxxx";
streamWriter.Write(data);
}
var response = (HttpWebResponse)request.GetResponse();
{
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
MessageBox.Show(result);
}
response.Close();
}
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);
}
I do not have a problem getting tokens in the desktop application I developed. But when I try to send data, I get a 401 error.
HttpWebRequest webRequest;
string requestParams = "";
webRequest = (HttpWebRequest)WebRequest.Create("url");
webRequest.Credentials = CredentialCache.DefaultCredentials;
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
webRequest.Headers.Add("x-api-key", "112233");
webRequest.Headers.Add("AccessToken", token);
byte[] byteArray = Encoding.UTF8.GetBytes(req);
webRequest.ContentLength = byteArray.Length;
using (Stream requestStream = webRequest.GetRequestStream())
{
requestStream.Write(byteArray, 0, byteArray.Length);
}
using (WebResponse response = webRequest.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
StreamReader rdr = new StreamReader(responseStream, Encoding.UTF8);
string Json = rdr.ReadToEnd();
}
}
The problem is about setting the token. First, you need to be sure what your server wants as a token. You can try this for the Bearer token.
webRequest.Headers.Add("Authorization", "Bearer " + token);
For your program to work, you have to provide an actual URL, not just the string "url", in
webRequest = (HttpWebRequest)WebRequest.Create("url");
Post to api with c # windows form application. oauth2.0
using (var client1 = new HttpClient ())
{
client1.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client1.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token());
client1.DefaultRequestHeaders.Add("x-api-key", "xxxx");
var builder = new UriBuilder(new Uri("you - url"));
HttpRequestMessage request1 = new HttpRequestMessage(HttpMethod.Post, builder.Uri);
request1.Content = new StringContent("{\"values\":" + JsonConvert.SerializeObject("you -data")+ "}", Encoding.UTF8, "application/json");
HttpResponseMessage response = await client1.SendAsync(request1);
};
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 want to do the following cURL request in c#:
curl -u admin:geoserver -v -XPOST -H 'Content-type: text/xml' \
-d '<workspace><name>acme</name></workspace>' \
http://localhost:8080/geoserver/rest/workspaces
I have tried using a WebRequest:
string url = "http://localhost:8080/geoserver/rest/workspaces";
WebRequest request = WebRequest.Create(url);
request.ContentType = "Content-type: text/xml";
request.Method = "POST";
request.Credentials = new NetworkCredential("admin", "geoserver");
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes("<workspace><name>my_workspace</name></workspace>");
Stream reqstr = request.GetRequestStream();
reqstr.Write(buffer, 0, buffer.Length);
reqstr.Close();
WebResponse response = request.GetResponse();
...
But I get an error: (400) Bad request.
If I change the request credentials and add the authentication in the header:
string url = "http://localhost:8080/geoserver/rest/workspaces";
WebRequest request = WebRequest.Create(url);
request.ContentType = "Content-type: text/xml";
request.Method = "POST";
string authInfo = "admin:geoserver";
request.Headers["Authorization"] = "Basic " + authInfo;
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes("<workspace><name>my_workspace</name></workspace>");
Stream reqstr = request.GetRequestStream();
reqstr.Write(buffer, 0, buffer.Length);
reqstr.Close();
WebResponse response = request.GetResponse();
...
Then I get: (401) Unauthorised.
My question is: Should I use another C# class like WebClient or HttpWebRequest or do I have to use the curl bindings for .NET?
All comments or guidance would be appreciated.
HTTP Basic authentication requies everything after "Basic " to be Base64-encoded, so try
request.Headers["Authorization"] = "Basic " +
Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo));
The solution to my question was changing the ContentType property. If I change the ContentType to
request.ContentType = "text/xml";
the request works in both cases, if I also convert the authInfo to a Base64String in the last example like Anton Gogolev suggested.
Using:
request.ContentType = "application/xml";
request.Credentials = new NetworkCredential(GEOSERVER_USER, GEOSERVER_PASSWD);
also works. The second sets authentication information.
Or, if you want to use HttpClient:
var authValue = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes("admin:geoserver")));
try
{
var client = new HttpClient()
{
DefaultRequestHeaders = { Authorization = authValue }
};
string url = "http://{BASE_URL}";
client.BaseAddress = new Uri(url);
var content = new StringContent("<workspace><name>TestTestTest</name></workspace>",
Encoding.UTF8, "text/xml");
var response = await client.PostAsync($"/{PATH_TO_API}/", content);
response.EnsureSuccessStatusCode();
var stringResponse = await response.Content.ReadAsStringAsync();
}
catch (HttpRequestException ex)
{
Console.WriteLine(ex.Message);
}