Converting PHP CURL query to C#'s HttpWebRequest - c#

I'm using HttpWebRequest in C# to do a POST to a particular API. The problem is that the system on the other end does not receive the body of the request. More so, when trying to send the request via tools like Postman, I have the same issue. The only thing that seems to work is a PHP implementation, detailed below.
My best guess is that I'm missing some header or another that the PHP sets automatically.
Has anybody encountered a similar problem/does anyone have a clue what I'm missing?
Both implementations below.
<?php
error_reporting(E_ALL);
$url = <<the APIs url>>
$hash = base64_encode('<<username>>:<password>>');
$data = [];
$username = <<username>>
$password =<password>>
$data = array(array(
"id" => "9999999",
"status" => 1,
<<rest of the formated data>>
));
$requestData = array(
'data' => $data,
'hash' => $hash
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($requestData));
$result = curl_exec($ch);
// $result = json_decode($result, true);
curl_close($ch);
die('done :'.$result);
?>
And here the C# implementation:
var httpWebRequest = (HttpWebRequest)WebRequest.Create(this.api_url);
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
httpWebRequest.KeepAlive = true;
httpWebRequest.Date = DateTime.Now.Date;
httpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
httpWebRequest.Headers.Add("Authorization", "Basic " + Base64Encode(userName + ":" + password));
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
tring requestResult = null;
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
requestResult= streamReader.ReadToEnd();
}

If you are posting JSON data, you should set the content type to application/json.

Related

How to POST request for authorization token from filemaker API in c#

I am hitting a POST request to a FileMaker API to get an authorization token but its throwing web exception. How can I fix it?
I have tried it in java. Now I am trying it in c# .NET framework 4.6.1
private static void GetToken(string username, string password)
{
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://exchange.furniflair.com/fmi/data/v1/databases/FurniflairDB/sessions");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
var bytes = Encoding.UTF8.GetBytes("dataapi:Data4me");
string temp = Convert.ToBase64String(bytes);
httpWebRequest.Headers.Add("Authorization", "Basic ZGF0YWFwaTpEYXRhNG1l");
string token;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
token = streamReader.ReadToEnd();
}
}
catch (WebException ex){}
}
I expect the output to be the authorization token in response, but I am getting only exceptions like httpWebException.
If it helps you set the headers correctly, here is an example that works using PHP.
$Post_Json = '{}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_PORT,443);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $Post_Json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$result=curl_exec ($ch);
This comes from: https://schwarzsoftware.com.au/blogentry.php?id=19
Also ensure that the Data API is turned on in the FileMaker Admin server console, and enabled for the FileMaker file you are trying to access, and access priviliges enabled for that user in the FileMaker file.

Https Post with .crt and .key

I am sorry if it is duplicate. I see a couple of post over the internet about this topic. But do not get any appropriate solution. I am working at nopcommerce 4.0, which is run on the .net core but the targeted framework is 4.x.x. I am developing a payment plugin which needs secure connection with .crt and .key files. The payment method provider sends a php file which is working as expected. Below is the sample code
function ProcessRequest($curl_post_data,$service_url,$proxy,$proxyauth)
{
$output = '';
$certfile = '/createorder.crt';
$keyfile = '/createorder.key';
$cert_password = '';
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $service_url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt( $ch, CURLOPT_SSLCERT, getcwd() . $certfile );
curl_setopt( $ch, CURLOPT_SSLKEY, getcwd() . $keyfile );
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$output = curl_exec($ch);
if (curl_error($ch)) {
echo $error_msg = curl_error($ch);
}
$cblcz = json_decode($output, true );
return $cblcz;
}
$proxy ="";
$proxyauth ="";
$postDatatoken = '{
"password": "123456Aa",
"userName": "test"
}';
$serviceUrltoken ="";
$serviceUrltoken= 'https://sandbox.thecitybank.com:7788/transaction/token';
$cblcz = ProcessRequest($postDatatoken,$serviceUrltoken,$proxy,$proxyauth);
I can not convert this curl to http post. I tried below link
PHP/Curl-SSL operations alternative in C# and others but do not get any work around.
Do not work. For openssl it is throwing dependency are not loaded. Here is my c# code
try
{
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12
| SecurityProtocolType.Ssl3;
var certPath = Path.Combine(CommonHelper.MapPath("~/Plugins/Payments.CityBankApi/"), "createorder.crt");
var keyPath = Path.Combine(CommonHelper.MapPath("~/Plugins/Payments.CityBankApi/"), "createorder.key");
string certificateText = File.ReadAllText(certPath);
string privateKeyText = File.ReadAllText(keyPath);
ICertificateProvider provider = new CertificateFromFileProvider(certificateText, privateKeyText);
//X509Certificate certificate = provider.Certificate;
string accessTokenUrl = "https://sandbox.thecitybank.com:7788/transaction/token";
var requestUrl = new Uri(accessTokenUrl);
var request = (HttpWebRequest)WebRequest.Create(accessTokenUrl);
request.ContentType = "application/json";
request.Method = "POST";
request.ClientCertificates.Add(provider.Certificate);
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = "{\"userName\":\"test\"," +
"\"password\":\"123456Aa\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
catch (Exception ex)
{
throw ex;
}
Your code seems correct. But make sure you have valid certificate. If the certification is not correct it will through an exception. Check your exception message and try to detect exact error. OR post your error message here.
moreover you should add
request.ServerCertificateValidationCallback = (e,r,c,n) => true;

Send Parameter HttpWebRequest return XML

Good morning,
I am trying to connect to a payment gateway which sends you a post parameters using HttpWebRequest.
The code that has done in the api is php but I need in C#.
function send_trans($url, $postData) {
$headers = array( 'Connection: Keep-Alive',
'Content-Type: application/x-www-form-urlencoded');
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko
/20080311 Firefox/2.0.0.13');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 40); // timeout en 40 segundos
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$xml = curl_exec($ch);
curl_close($ch);
return ($xml);
}
have tried it with the following code.
  
 
public static string HttpPostRequest (string url, Dictionary <string, string> postParameters)
        {
            string postData = "";
            foreach (string key in postParameters.Keys)
            {
                postData + = key + "=" + postParameters [key] + "&";
            }
            HttpWebRequest myHttpWebRequest = (HttpWebRequest) HttpWebRequest.Create (url);
            myHttpWebRequest.Method = "POST";
            byte [] data = Encoding.ASCII.GetBytes (postData);
            myHttpWebRequest.ContentType = "application / x-www-form-urlencoded";
            myHttpWebRequest.ContentLength = data.Length;
            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, Encoding.Default);
            string pageContent = myStreamReader.ReadToEnd ();
            myStreamReader.Close ();
            responseStream.Close ();
            myHttpWebResponse.Close ();
            return pageContent;
        }
the error it gives me is in the line of Stream responseStream = myHttpWebResponse.GetResponseStream (), I have tried with other code and it is always the same error in GetResponseStream.

c# equivalent of md5 in PHP

I have a code which looks like this, It's basically a JSON request which I need to pass to the server and code in PHP looks like this:
<?php
$client_secret= '';
$data= array(
'email' => '**********',
'password' => '******',
'client_id' => '*******'
);
$api_url='******';
$json_data=json_encode($data);
$signature_string = md5($json_data . $client_secret);
$post_data = 'signature='.$signature_string.'&data='.urlencode($json_data);
$curl = curl_init($api_url);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
$result = curl_exec($curl);
print_r($result);
curl_close($curl);
?>
And this works fine in PHP. So now I'm trying to translatet this code into C#.
What I did so far is:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
string client_secret = "*****";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"email\":\"******\"," +
"\"password\":\"******\"}" +
"\"client_id\":\"******\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
string resp = string.Empty;
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
resp = streamReader.ReadToEnd();
}
return resp;
Basically I now have my data in JSON format. What now I need to do is replicate the PHP's md5 function to create a MD5 hash out of my client_secret string + JSON string which was created in previous step and then simply post the data string to server.
Can someone help me out with this ?

C# Basic Authentication from curl request

I have curl request and i'd like create analog to C#. Bat all my attempts have failed. I tried everything I could find in google. This description API https://github.com/onlinerby/onliner-b2b-api/blob/master/docs/oauth20.md
this curl
$process = curl_init("https://b2bapi.onliner.by/oauth/token");
curl_setopt($process, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($process, CURLOPT_USERPWD, "204da9b95e2480a3455f:7a4bbb61262fdf41d410645292a0489ba752c6b9");
curl_setopt($process, CURLOPT_POST, 1);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($process, CURLOPT_POSTFIELDS, array('grant_type' => 'client_credentials'));
$result = curl_exec($process);
curl_close($process);`
this my c# code
string url = "https://b2bapi.onliner.by/oauth/token";
WebClient client = new WebClient();
client.Headers["Accept"] = "application/json";
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("204da9b95e2480a3455f:7a4bbb61262fdf41d410645292a0489ba752c6b9"));
client.Headers[HttpRequestHeader.Authorization] = "Basic " + credentials;
var result = client.UploadString(url, "grant_type=client_credentials");`
please help me, i am lost a lot time ...

Categories

Resources