0

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?
jubi
  • 569
  • 1
  • 10
  • 34
  • What exactly do you mean by "decoded values"? – ProgrammingLlama Oct 18 '19 at 02:34
  • Some symbols like 0<>...some invalid characters. – jubi Oct 18 '19 at 02:38
  • Can you edit your question to include actual examples of what you expect vs what you're getting. – ProgrammingLlama Oct 18 '19 at 02:39
  • I am getting respose from IssussessStatusCode: true{ Response { file Name : "sample", readable :true} } . This is the actual response from api call – jubi Oct 18 '19 at 02:40
  • [Maybe related](https://stackoverflow.com/questions/20990601/decompressing-gzip-stream-from-httpclient-response) – ProgrammingLlama Oct 18 '19 at 02:41
  • Please remember to _edit_ your question to include more information, as opposed to providing it in comments. – ProgrammingLlama Oct 18 '19 at 02:44
  • The difference i feel from the request body is name=\"\" is not able to send through my C# code. How do i get the similar value. If i add as shown in example as Name = " " is is giving a space . How do i pass name=\"\" exactle as in postman – jubi Oct 18 '19 at 02:44
  • In Postman, the `name=\"\"` is inside a string. The backslashes are simply escaping the quotes so they don't incorrectly terminate the string. If you don't want a space in the name (to mimic what's happening with Postman), just don't put a space in it: `Name = ""`. Whether that's the cause of the issue, I can't say. – erichamion Oct 18 '19 at 04:16
  • @john here i have the file in my local folder. Can you suggest me if the file is in a blob location and what i have is the url of the file – jubi Oct 18 '19 at 06:26

1 Answers1

4

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.

HariHaran
  • 3,642
  • 2
  • 16
  • 33
  • Yes this is right. In my case I was calling - https://use.fontawesome.com/releases/v4.7.0/css/font-awesome-css.min.css and had to use DecompressionMethods.Brotli – Varun Sharma Jul 11 '21 at 22:31