How to convert C# RestSharp to C# ASP.NET httpclient - c#

below codes is the generated c# restsharp codes from postman. How can I convert it to c# asp.net mvc4 codes for httpclient. When trying to debug in VS, I always have error of bad request. This is for ebay api creating a shipping fulfillment. Tested in postman works with the codes below.
var client = new RestClient("https://api.ebay.com/sell/fulfillment/v1/order/23-00000-11313/shipping_fulfillment");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Content-Language", "en-US");
request.AddHeader("Accept-Language", "en-US");
request.AddHeader("Accept-Charset", "utf-8");
request.AddHeader("Accept", "application/json");
request.AddHeader("Authorization", "Bearer v^1.1#i^1#I^3#f^0#p^3#r^0#t^H4sIAAAAA==");
request.AddParameter("application/json", "{\"lineItems\":[{\"lineItemId\":\"10022882297723\",\"quantity\":1}],\"shippedDate\":\"2020-02-11T01:28:16.475Z\",\"shippingCarrierCode\":\"Couriers Please\",\"trackingNumber\":\"UHV3436755010009000000\"}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Current codes in asp.net but having error bad request.
private HttpClient CreateHttpClient()
{
var client = new HttpClient();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
string baseAddress = WebApiBaseAddress;
if (string.IsNullOrEmpty(baseAddress))
{
throw new HttpRequestException("There is no base address specified in the configuration file.");
}
client.Timeout = new TimeSpan(0, 5, 59);
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Authorization", string.Format("Bearer {0}", _cred.eBayToken));
client.DefaultRequestHeaders.Add("Accept-Language", "en-US");
client.DefaultRequestHeaders.Add("Accept-Charset", "utf-8");
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("LegacyUse", "true");
return client;
}
public HttpResponseMessage PostHttpResponse(string requestUri, object data)
{
var stringPayload = JsonConvert.SerializeObject(data);
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
httpContent.Headers.Add("Content-Language", "en-US");
httpContent.Headers.Add("Content-Encoding", "gzip");
using (var client = CreateHttpClient())
{
try
{
HttpResponseMessage response = client.PostAsJsonAsync(requestUri, httpContent).Result;
if (response.IsSuccessStatusCode)
{
return response;
}
else
{
GetErrorsResponse(response);
throw new HttpRequestException(string.Format("There was an exception trying to post a request. response: {0}", response.ReasonPhrase));
}
}
catch (HttpRequestException ex)
{
throw ex;
//return null;
}
}
}
Thank in advance for the help. It is very much appreciated.

Related

RestSharp to HttpClient

var client = new RestClient("http://10.0.0.244:8885/terminal/info");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("apikey", "adasdsadasd");
var body = #"{}";
request.AddParameter("application/json", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Could someone, please, help me write this code with HttpClient?
I try following code.
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://10.0.0.244:8885/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Clear();
HttpRequestMessage request = new HttpRequestMessage();
request.Method = HttpMethod.Post;
request.RequestUri = new Uri($"{client.BaseAddress}/terminal/info");
request.Headers.Add("apikey", "adasdsadasd");
var body = Newtonsoft.Json.JsonConvert.SerializeObject(new { });
request.Content = new StringContent(body, Encoding.UTF8, "application/json");//CONTENT-TYPE header
request.Content.Headers.Clear();
request.Content.Headers.ContentLength = 2;
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.SendAsync(request).GetAwaiter().GetResult();
var x = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
}
But it response with Status Code 400 (ParseError)
You can accomplish what you are trying to do with much less code. Also this should be in an async method. Below is an example
internal async Task<string> GetResponse()
{
using var client = new HttpClient();
client.BaseAddress = new Uri("http://10.0.0.244:8885/");
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("apikey", "adasdsadasd");
var content = new StringContent("{}", Encoding.UTF8, "text/plain");
var response = await client.PostAsync("/terminal/info", content);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
return null;
}

401.0000007 Error while trying to get the DHL Interface C# code. Followed DHL document

I have been trying to connect to DHL interface but i cannot get the token access key from C# code. here is my current code. Please let me know if you have a solution -
RestClient client = new RestClient();
client.ClearHandlers();
client.Timeout = -1;
client.BaseUrl = new Uri("https://api-sandbox.dhlecs.com/auth/v4/accesstoken");
client.Authenticator = new HttpBasicAuthenticator(ConfigurationManager.AppSettings["DHLClientId"], ConfigurationManager.AppSettings["DHLClientSecret"]);
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Accept", "application/json");
request.Parameters.Clear();
request.AddParameter("grant_type", "client_credentials");
IRestResponse response = client.Execute(request);
var local = response.Content.ToString();
if (response.StatusCode == HttpStatusCode.OK)
{
return response.Content.ToString();
}
else
{
throw new Exception($#"Unable to authorize with GLS. Contact IT");
}
here is the error i get -
https://api-sandbox.dhlecs.com/docs/errors/401.0000007"
>> Solution :
this needs to be removed -
request.Parameters.Clear();

How to call a httpClient request - response is giving decoded value

I have used postman to send a post request by attaching a file in the request body. Below is the postman request sample. I got success response with the response content.
var client = new RestClient("https://***********");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Connection", "keep-alive");
request.AddHeader("Content-Length", "757");
request.AddHeader("Accept-Encoding", "gzip, deflate");
request.AddHeader("Host", "**********");
request.AddHeader("Postman-Token", "********");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Accept", "*/*");
request.AddHeader("User-Agent", "PostmanRuntime/7.18.0");
request.AddHeader("Authorization", "Bearer XX");
request.AddHeader("Content-Type", "multipart/form-data");
request.AddHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundaryabc");
request.AddParameter("multipart/form-data; boundary=----WebKitFormBoundaryabc", "------WebKitFormBoundaryabc\r\nContent-Disposition: form-data; **name=\"\"**; filename=\"sample.csv\"\r\nContent-Type: text/csv\r\n\r\n\r\n------WebKitFormBoundaryabc--", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Actual expected response from api call using postman is:
IssussessStatusCode: true{ ResponseData { file Name : "sample", readable :true} }
I have used C# httpClient method as below to do the same call
using (var _httpClient = new HttpClient())
{
using (var stream = File.OpenRead(path))
{
_httpClient.DefaultRequestHeaders.Accept.Clear();
_httpClient.DefaultRequestHeaders.Add("Accept", "*/*");
_httpClient.DefaultRequestHeaders.Add("cache-control", "no-cache");
_httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate");
_httpClient.DefaultRequestHeaders.Add("Host", "*********");
_httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer XX");
_httpClient.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data")); // ACCEPT header
var content = new MultipartFormDataContent();
var file_content = new ByteArrayContent(new StreamContent(stream).ReadAsByteArrayAsync().Result);
file_content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
file_content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
FileName = "sample.csv",
**Name = " ", // Is this correct. In postman request it is **name=\"\"****
};
content.Add(file_content);
_httpClient.BaseAddress = new Uri("**************");
var response = await _httpClient.PostAsync("****url", content);
if (response.IsSuccessStatusCOde)
{
string responseBody = await response.Content.ReadAsStringAsync();
}
}
}
I am getting tresponse this way
Result: "\u001f�\b\0\0\0\0\0\u0004\0�\a`\u001cI�%&/m�{\u007fJ�J��t�\b�`\u0013$ؐ#\u0010������\u001diG#)�*��eVe]f\u0016#�흼��{���{���;�N'���?\\fd\u0001l��J�ɞ!���\u001f?~|\u001f?\"~�G�z:͛�G�Y�䣏��\u001e�⏦�,�������G\vj�]�_\u001f=+�<����/��������xR,�����4+�<�]����i�q��̳&O���,�\u0015��y�/۴�/�����r�������G��͊�pX������\a�\u001ae_�\0\0\0"
Here I get some decoded values when I execute `response.Content.ReadAsStringAsync();`
Can someone help me on what needs to be done here?
Ok , i understand your problem. The api is returning response in a compressed format. You need to Deflate/Gzip it. I have faced similar problems earlier. Try my solution.
You need to make use of the HttpClientHandler() class like this.
var httpClientHandler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip
};
_httpClient = new HttpClient(httpClientHandler);
When the httpClient gets instantiated, you need to pass in the handler in the first place.

How to call Rest API with Content and Headers in c#?

I am trying to call Rest API with content and headers in c#. Actually I am trying to convert to c# from Python code which is:
import requests
url = 'http://url.../token'
payload = 'grant_type=password&username=username&password=password'
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.request('POST', url, headers = headers, data = payload, allow_redirects=False)
print(response.text)
So far I am trying with:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(Url);
var tmp = new HttpRequestMessage
{
Method = HttpMethod.Post,
Content =
{
}
};
var result = client.PostAsync(Url, tmp.Content).Result;
}
I have no idea how to put from Python code Headers (Content-Type) and additional string (payload).
If you use RestSharp, you should be able to call your service with the following code snipped
var client = new RestClient("http://url.../token");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=password&username=username&password=password", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var result = response.Content;
I based my answer on the anwser of this answer.
Here a sample I use in one of my apps:
_client = new HttpClient { BaseAddress = new Uri(ConfigManager.Api.BaseUrl),
Timeout = new TimeSpan(0, 0, 0, 0, -1) };
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
_client.DefaultRequestHeaders.Add("Bearer", "some token goes here");
using System.Net.Http;
var content = new StringContent("grant_type=password&username=username&password=password");
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
client.PostAsync(Url, content);
Or use FormUrlEncodedContent without set header
var data = new Dictionary<string, string>
{
{"grant_type", "password"},
{"username", "username"},
{"password", "password"}
};
var content = new FormUrlEncodedContent(data);
client.PostAsync(Url, content);
If you write UWP application, use HttpStringContent or HttpFormUrlEncodedContent instead in Windows.Web.Http.dll.
using Windows.Web.Http;
var content = new HttpStringContent("grant_type=password&username=username&password=password");
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
client.PostAsync(Url, content);
var data = new Dictionary<string, string>
{
{"grant_type", "password"},
{"username", "username"},
{"password", "password"}
};
var content = new FormUrlEncodedContent(data);
client.PostAsync(Url, content);

500 Server Error when calling REST API over HTTPS

I'm using this code to POST XML to a REST webservice, but am just getting a vague '500 Server Error'. If I paste the same XML into Fiddler it works perfectly, so what am I doing wrong?
using (var client = new HttpClient())
{
var httpContent = new StringContent(doc.ToString(), Encoding.UTF8, "text/xml");
var response = client.PostAsync(new Uri("httpsapiurl"),httpContent).Result;
if (response.IsSuccessStatusCode)
{
// EDITED: this isn't hit as IsSuccessStatusCode is always false
//Stream stream = await response.Content.ReadAsStreamAsync();
}
}
Could it be that you need to set the Content type on the request?
try
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, URL);
req.Content = new StringContent(doc.ToString(), Encoding.UTF8, "text/xml");
await httpClient.SendAsync(req).ContinueWith(async respTask =>
{
Debug.WriteLine(req.Content.ReadAsStringAsync());
};
}
catch (Exception ex)
{
}
Especially this line is important. I had similar problem with an API that refused to spit anything back when not setting the Content-Type header correct.
req.Content = new StringContent(doc.ToString(), Encoding.UTF8, "text/xml");
Don't know if it can help.

Categories

Resources