Http Request to download file from remote server - c#

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#

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");

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 construct HttpClient POST Request with form-data in C#?

I am having issues constructing the POST request with form-data in C# using HTTPClient. i tried multiple approaches but nothing seems to work. Can you please help what I am missing?
Please be informed, the SWAGGER POST is working fine and based on that I am trying to construct the request.
The API parameters
rPath* string
(formData)
nName* string
(formData)
nFile string
(formData)
type* string
(formData)
zFile file
file
The working swagger POST
curl -X POST "http://localhost:8888/server/api/v1.0/createfolder" -H "accept: text/plain; charset=UTF-8" -H "authorization: Basic XXXXXXX" -H "Content-Type: multipart/form-data" -F "rPath=/RootFolder/" -F "nName=testing" -F "type=Folder"
The Fiddler request header of the SWAGGER POST (This is working).
static void Main(string[] args)
{
var formData = new MultipartFormDataContent();
HttpContent content = new FormUrlEncodedContent (new[]
{
new KeyValuePair<string, string>("rPath", "/RootFolder/"),
new KeyValuePair<string, string>("nName", "TestFolder"),
new KeyValuePair<string, string>("type", "Folder")
});
content.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
formData.Add(content);
var url = "http://localhost:8888/server/api/v1.0/createfolder";
HttpResponseMessage response = PostRoot(formData, url);
}
static HttpResponseMessage PostRoot(HttpContent content, string webMethod)
{
HttpResponseMessage response = new HttpResponseMessage();
using (var client = new HttpClient() { })
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "xxxxxxx=");
response = client.PostAsync(webMethod, content).Result;
}
return response;
}
Here's an example of how to send multi part form data:
var client = new HttpClient();
var baseUrl = "https://someurl";
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "multipart/form-data");
var formContent = new MultipartFormDataContent
{
{new StringContent("ParamValue1"),"ParamName1"},
{new StringContent("ParamValue2"),"ParamName2"},
{new StringContent("ParamValue2"),"ParamName3"},
};
var response = client.PostAsync(baseUrl, formContent).Result;
response.EnsureSuccessStatusCode();
var result = string.Empty;
if (response.IsSuccessStatusCode)
{
result = response.Content.ReadAsStringAsync().Result;
}
return result;

Time out error: HttpClient POST

I'm having trouble making POST using http client with Accept, ContentType and Authentication as headers. I tried several implementations using send aysnc and post async and all seemed to fail. I used https://www.hurl.it/ to make sure if it also was getting a time out error but it is working, getting back json data.
I get a connection time out error exception (in: var response = await client.SendAsync(request);) when running the below code.
Also I have curl command which i was trying to go off by, which is listed below as well.
Implementation:
// Body
var dictionary = new Dictionary<string, string>();
dictionary.Add("id", "123");
var formData = new List<KeyValuePair<string, string>>();
formData.Add(new KeyValuePair<string, string>("id", "123"));
// Http Client
var client = new HttpClient();
client.BaseAddress = new Uri("https://www.some_website.com/api/house");
// Http Request
var request = new HttpRequestMessage(HttpMethod.Post, "https://www.some_website.com/api/house");
// Accept
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Content-Type
//request.Content = new FormUrlEncodedContent(dictionary);
var httpContent = new StringContent(
JsonConvert.SerializeObject(
dictionary,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
}),
Encoding.UTF8,
"application/json");
request.Content = new StringContent(
JsonConvert.SerializeObject(
dictionary,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
}),
Encoding.UTF8,
"application/json");
// Authentication
var byteArray = new UTF8Encoding().GetBytes("user" + ":" + "pass");
//client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var header = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
client.DefaultRequestHeaders.Authorization = header;
// Communication
try
{
var response = await client.SendAsync(request);//PostAsync("https://www.some_website.com/api/house", httpContent);
if (response.IsSuccessStatusCode)
{
var myContent = await response.Content.ReadAsStringAsync();
var deliveryStatus = JsonConvert.DeserializeObject<MyOjbect>(myContent);
}
}
catch (Exception e)
{
//catch error
}
Curl:
curl -i --user user:123 -H Accept:application/json -H content-type:application/json -H cache-control:no-cache -X POST https://www.some_website.com/api/house -H Content-Type: application/json -d '{"id": "123"}'
You set your BaseAddress and the HttpRequestMessage Uri property both to the same absolute url, shouldn't it be the base address (ex. somewebsite.com) and the relative url (ex. (api/house). You can also inspect your request with Fiddler telerik.com/fiddler

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