How to Convert this curl to RestSharp - c#

I have problem with converting this curl request to RestSharp it return 404 error, note the URL is correct.
I think the problem is come from -d parameter.
curl -v -X POST https://sandbox.bluesnap.com/services/2/transactions \
-H 'Content-Type: application/xml' \
-H 'Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=' \
-d '
<card-transaction xmlns="http://ws.plimus.com">
<card-transaction-type>AUTH_CAPTURE</card-transaction-type>
<recurring-transaction>ECOMMERCE</recurring-transaction>
<soft-descriptor>DescTest</soft-descriptor>
<amount>11.00</amount>
<currency>USD</currency>
<card-holder-info>
<first-name>test first name</first-name>
<last-name>test last name</last-name>
</card-holder-info>
<credit-card>
<card-number>4263982640269299</card-number>
<security-code>837</security-code>
<expiration-month>02</expiration-month>
<expiration-year>2018</expiration-year>
</credit-card>
</card-transaction>'
I did some thing like this:
var client = new RestClient("https://sandbox.bluesnap.com/services/2/transactions");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "Content-Type: application/xml");
client.Authenticator = new HttpBasicAuthenticator("username", "password");
request.AddBody(GetXmlToSend(record, CriditCardInfo));
IRestResponse response = client.Execute(request);
var content = response.Content;
var response2 = client.Execute<dynamic>(request);

When you instantiate a new RestClient you should use the base url, e.g.:
var client = new RestClient("https://sandbox.bluesnap.com");
Then when you create the RestRequest you should be passing the path to the resource:
var request = new RestRequest("services/2/transactions", Method.POST);

write your xml data to a file, say file.xml
RestClient client = new RestClient(baseUrl);
RestRequest request = new RestRequest(remainingPartOfURL, Method.POST);
client.Authenticator = new HttpBasicAuthenticator(userId, password);
request.AddHeader("Content-Type", "application/xml");
request.AddHeader("Accept", "application/json");
request.AddFile("myFile", "D:\\file.xml");
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
IRestResponse response = client.Execute(request);
if (response != null)
Console.WriteLine(response.Content);
IF you are invoking this code within Office environment then you need to provide proxy server info. You can get proxy server info from Settings->"Network and Internet"->Proxy
NetworkCredential aCredentials = new NetworkCredential();
aCredentials.Domain = "";
aCredentials.UserName = "";
aCredentials.Password = "";
WebProxy aProxy = new WebProxy();
aProxy.Address = new Uri("http://proxyserver.com:8080");
aProxy.Credentials = aCredentials;
client.Proxy = aProxy;

Related

Creating Postman request in C#

I am able to make the following request in Postman but not able to in C#. I'm guessing it's due to the json but tried a few different ways and still nothing.
Postman:
curl --location --request POST 'https://login.sandbox.payoneer.com/api/v2/oauth2/token' \
--header 'Authorization: Basic *ENCRYPTEDPASSCODE FROM ClientID & Secret*' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=client_credentials' \
--data-urlencode 'scope=read write'
My Code returns text "ErrorParams":null:
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, $"https://login.sandbox.payoneer.com/api/v2/oauth2/token");
var authString = $"{clientID}:{secret}";
var encodedString = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(authString));
request.Headers.Add("Authorization", $"Basic {encodedString}");
string json = JsonConvert.SerializeObject(new
{
grant_type = "client_credentials",
scope = "read write"
});
request.Content = new StringContent(json, Encoding.UTF8, "application/x-www-form-urlencoded");
var response = await client.SendAsync(request).ConfigureAwait(false);
var responseText = await response.Content.ReadAsStringAsync();
return responseText;
If you need to set the content as application/x-www-form-urlencoded then use FormUrlEncodedContent
var dict = new Dictionary<string, string>();
dict.Add("grant_type", "client_credentials");
dict.Add("scope", "read write");
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, $"https://login.sandbox.payoneer.com/api/v2/oauth2/token") { Content = new FormUrlEncodedContent(dict) };
var response = await client.SendAsync(request).ConfigureAwait(false);
var responseText = await response.Content.ReadAsStringAsync();
If you are serializing the request body to JSON, then you need to set the Content-Type as application/json
request.Headers.Add("Content-Type", "application/json");

Http Request to download file from remote server

I am trying to translate the following curl command
curl --location --request GET "https://xxx.xxxx.xxx/artifacts?session=016e1f70-d9da-41bf-b93d-80e281236c46&path=/home/gauntlet_gameye/LinuxServer/Game/Saved/Logs/Game.log" -H "Authorization:Bearer xxxx" -H "Accept:application/json" --output C:\Temp\Game.log
To C# code and I have the following
string SessionId = "016e1f70-d9da-41bf-b93d-80e281236c46";
string Token = "xxxx";
string FilePath = "/home/gauntlet_gameye/LinuxServer/Game/Saved/Logs/Game.log";
string Endpoint = string.Format("https://xxx.xxxx.xxx/artifacts?session={0}&path={1}", SessionId, FilePath);
HttpRequestMessage HttpRequestMsg = new HttpRequestMessage();
HttpRequestMsg.RequestUri = new Uri(Endpoint);
HttpRequestMsg.Method = HttpMethod.Get;
HttpRequestMsg.Headers.Add("Accept", "application/json");
HttpRequestMsg.Headers.Add("Authorization", string.Format("Bearer {0}", Token));
HttpRequestMsg.Content = new StringContent(string.Format("--output {0}", OutFilePath), Encoding.UTF8, "application/json");
using (HttpClient Client = new HttpClient())
{
var HttpResponseTask = Client.SendAsync(HttpRequestMsg);
}
But it gives me the following exception info
Cannot send a content-body with this verb-type.
--location and --output are not C# supported options
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://xxx.xxxx.xxx/artifacts?session=016e1f70-d9da-41bf-b93d-80e281236c46&path=/home/gauntlet_gameye/LinuxServer/Game/Saved/Logs/Game.log");
request.Headers.Add("Authorization", "Bearer xxxx");
request.Headers.Add("Accept", "application/json");
HttpResponseMessage response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Source: Convert curl commands to C#

How to send http from with POST method without URLEncoding in unity?

I'm trying to send some data to a server using POST in unity but because unity url-encodes the data when using UnityWebRequest.Post() I'm getting 404 error from server, so I want to constract request myself however I'm still getting same error.
the curl request is something like this:
curl -X 'POST' \
'https://[server url].com/api/v1/client/match/195' \
-H 'accept: application/json' \
-H 'Authorization: Bearer eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0...' \
-H 'Content-Type: multipart/form-data' \
-F 'Data=1647396005200|7Q3E1dEzFnVDEdRtZbPEjBXkde+MGaWdzk9WJtmZF90='
I can send this data with .net without problem:
private static async Task SendRequestAsync(string url)
{
string Json = $"{{\"Score\":10,\"Time\":10}}";
string dataToSend = EncryptData(Json);
HttpClient client = new HttpClient();
var values = new Dictionary<string, string>
{
{ "Data", dataToSend }
};
client.DefaultRequestHeaders.Add("accept", "application/json");
client.DefaultRequestHeaders.Add("Authorization", AccessToken);
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "multipart/form-data");
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync(url, content);
var responseString = await response.Content.ReadAsStringAsync();
print(responseString);
}
But I want to use UnityWebRequest to archive the same result but I'm getting server error. this is the code for UnityWebRequest.
string Json = $"{{\"Score\":10,\"Time\":10}}";
var dataToSend = EncryptData(Json);
WWWForm form = new WWWForm();
form.AddField("Data", dataToSend, Encoding.UTF8);
var downloadHandlerRaw = new DownloadHandlerBuffer();
//var data = Encoding.UTF8.GetBytes(dataToSend);
request = new UnityWebRequest();
request.url = url;
request.method = UnityWebRequest.kHttpVerbPOST;
request.uploadHandler = new UploadHandlerRaw(form.data);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("accept", "application/json");
request.SetRequestHeader("Authorization", AccessToken);
request.SetRequestHeader("Content-Type", "multipart/form-data");
I don't know what I'm doing wrong, I have tried so many things but I can't make it work. how can I fix it? any help is appreciated, thanks.

How to get admin token in magento 2.1.8?

I'm trying to get an admin token from Magento version 2.1.8 in c# using well-known code that works for all except me. Could not understand where is the problem.
In response I get:
ErrorException = null, Content= "{\" message \ ": \" Request does not match any path. \ ", \" trace \ ": null}"
public Magento(string magentoUrl)
{
//Relative URL needs to be Specified
var endpoint = "/rest/V1/integration/admin/token";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var _restClient = new RestClient(magentoUrl);
var request = new RestRequest(endpoint, Method.POST);
//Initialize Credentials Property
var userRequest = new Credentials { username = "reewrew", password = "rwerwerw" };
var inputJson = JsonConvert.SerializeObject(userRequest);
//Request Header
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Accept", "application/json");
//Request Body
request.AddParameter("application/json", inputJson, ParameterType.RequestBody);
var response = _restClient.Execute(request);
var token = response.Content;
}
I found the problem. I use HTTP instead of HTTPS in URL.

Converting a curl command to a .NET http request

Could someone please help me convert this curl command into a HttpClient/HttpRequestMessage format in .NET?
curl https://someapi.com/ID \
-H "Authorization: Bearer ACCESS_TOKEN" \
-d '{"name":"test name"}' \
-X PUT
What I have so far is this, but it doesn't seem to be right:
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Put, url);
request.Headers.Add("Authorization", String.Format("Bearer {0}", accessToken));
request.Properties.Add("name", "test name");
return await client.SendAsync(request).ConfigureAwait(false);
Edit:
This example uses Json.NET to serialize the string to a json format
Try:
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var anonString = new { name = "test name" };
var json = JsonConvert.SerializeObject(anonString);
await client.PutAsync("URL", new StringContent(json)).ConfigureAwait(false);

Categories

Resources