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.
Related
TerminalAPIRequest terminalAPIRequest = new TerminalAPIRequest();
TerminalAPIResponse terminalAPIResponse = new TerminalAPIResponse();
var client = new RestClient("https://connect.squareupsandbox.com/v2/terminals/checkouts");
//client.Timeout = -1;
var request = new RestRequest("https://connect.squareupsandbox.com/v2/terminals/checkouts", Method.Post);
request.AddHeader("Square-Version", "2023-01-19");
request.AddHeader("Authorization", "Bearer token");
request.AddHeader("Content-Type", "application/json");
var body = JsonConvert.SerializeObject(terminalAPIRequest);
request.AddParameter("application/json", body, ParameterType.RequestBody);
var response = client.Execute(request);
Related Webhook Responses are found at webhook.site
. Now How can I get that response to My WPF application?
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;
}
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.
I am trying to send HttpClient PostAsync() request to company's internal sharepoint site but its returning response with forbidden error. I have all necessary access permission for site to load and have also passed required headers to the HttpClient object.
Here is code snippet.
HttpClient client = new System.Net.Http.HttpClient (new HttpClientHandler { UseDefaultCredentials = true });
client.BaseAddress = new Uri (string.Format (API_URL, p_siteNumber));
client.DefaultRequestHeaders.Accept.Add (new MediaTypeWithQualityHeaderValue (#"application/atom+xml"));
client.DefaultRequestHeaders.TryAddWithoutValidation ("Accept-Encoding", "gzip, deflate");
client.DefaultRequestHeaders.TryAddWithoutValidation ("Accept-Language", "en-US, en;q=0.8, hi;q=0.6");
client.DefaultRequestHeaders.TryAddWithoutValidation ("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0");
client.DefaultRequestHeaders.TryAddWithoutValidation ("Accept-Charset", "ISO-8859-1");
HttpResponseMessage httpResponse = await client.PostAsync (urlHttpPost, new StringContent (string.Empty));
string response = await httpResponse.Content.ReadAsStringAsync ();
Can anyone help me with this?
Thanks in advance.
I ran into the same problem I wanted to send the file and some string contents with it.
so below code helped me!!
using (var client = new HttpClient())
{
//client.DefaultRequestHeaders.Add("User-Agent", "CBS Brightcove API Service");
string authorization = GenerateBase64();
client.DefaultRequestHeaders.Add("Authorization", authorization);
using (var content = new MultipartFormDataContent())
{
string fileName = Path.GetFileName(textBox1.Text);
//Content-Disposition: form-data; name="json"
var stringContent = new StringContent(InstancePropertyObject);
stringContent.Headers.Remove("Content-Type");
stringContent.Headers.Add("Content-Type", "application/json");
stringContent.Headers.Add("Content-Disposition", "form-data; name=\"instance\"");
content.Add(stringContent, "instance");
var fileContent = new ByteArrayContent(filecontent);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = fileName
};
content.Add(fileContent);
var result = client.PostAsync(targetURL, content).Result;
}
}
This is driving me nuts, I am setting the ContentType header everywhere I can and can't seem to make it stop sending text/plain.
Watching the data in Fiddler, the request is always requesting:
POST http:/domain.com HTTP/1.1
Content-Type: text/plain; charset=utf-8
using (var httpClient = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, "http://domain.com");
request.Content = new StringContent(Serialize(obj), Encoding.UTF8, "text/xml");
request.Content.Headers.Clear();
request.Content.Headers.ContentType = new MediaTypeHeaderValue("text/xml");
request.Headers.Clear();
request.Headers.Add("Content-Type","text/xml");
var response = await httpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
It looks like you tried to hard :) This should just work.
using (var httpClient = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, "http://domain.com");
request.Content = new StringContent(Serialize(obj), Encoding.UTF8, "text/xml");
var response = await httpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
Try settings the default request headers:
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
Use "application/xml" instead of "text/xml"