cancel
Showing results for 
Search instead for 
Did you mean: 

Attachments2 using HttpClient and C#

Jorgedotnet
Discoverer
0 Kudos
198

Hi. Based on 

  • Postman tool OK
  • .NET B1SLayer OK
  • .NET System.Net.Http.HttpClient Failed

Assuming that the login has been previously performed with the SAPclient object. The Attachments2 method doesn't work with HttpClient in C#. Please see:

var res = "";
var content = new MultipartContent();
var outputFile = new StreamContent(new MemoryStream(File.ReadAllBytes("C:\\Users\\Jorge\\Postman\\files\\helloworld.txt)));

outputFile.Headers.Add("Content-Disposition", $"form-data; name=\"files\"; filename=\"helloworld.txt\"");
outputFile.Headers.Add("Content-Type", "application/octet-stream");
content.Add(outputFile);
var boundary = content.Headers.ContentType!.Parameters.First(o => o.Name.Equals("boundary", StringComparison.OrdinalIgnoreCase));
boundary.Value = boundary.Value!.Replace("\"", string.Empty);

var response = await SAPclient.PostAsync("https://mycompany.com:50000/b1s/v1/Attachments2", content);
if (response.IsSuccessStatusCode == true && response.StatusCode == HttpStatusCode.Created)
{
Attachments2Response? resA = await response.Content.ReadFromJsonAsync<Attachments2Response>();
res = resA!.AbsoluteEntry.ToString(); 
}

The Response: StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
Date: Thu, 12 Sep 2024 20:46:02 GMT
Server: Apache/2.4.54 (Unix)
DataServiceVersion: 3.0
Vary: Accept-Encoding
Connection: close
Transfer-Encoding: chunked
Content-Type: application/json;charset=utf-8
}}

Why and how to fix it?

Thanks.

Jorge

Accepted Solutions (0)

Answers (1)

Answers (1)

ANKIT_CHAUHAN
Product and Topic Expert
Product and Topic Expert
0 Kudos

Hi Jorgedotnet,

Can you use Fiddler tool to get the request (including all headers) which is being sent to Service Layer to process?

In the past, we have observed that Expect: 100-continue header is contained in the request which is not supported by Service Layer.

If it is the case, please add httpClient.DefaultRequestHeaders.ExpectContinue = false; in the code and check the issue again.

Kind regards,

ANKIT CHAUHAN

SAP Business One Support

Jorgedotnet
Discoverer
0 Kudos
Hi ANKIT. The same error with .NET httpClient. Based on Fiddler and Service Layer: POST /b1s/v1/Attachments2 HTTP/1.1 Host: mycompany.com:50000 Cookie: B1SESSION=5412064e-71c4-11ef-8000-12c57281de91; ROUTEID=.node4 Accept-Encoding: gzip, deflate Content-Type: multipart/form-data; boundary=c86cf448-3c24-4769-bcb5-fb30989a83d7 Content-Length: 214. Sincerely Jorge.
Jorgedotnet
Discoverer
0 Kudos
Hi a suggestion: Can you please reproduce this code on your side. Anything please feel free to contact me. Thanks. Jorge