简体   繁体   中英

How to replicate Postman POST request in C#

I'm fairly new to .NET's HTTPClient class, hence kindly excuse if I sounded noob. I'm tryin to replicate Postman's POST request in C# .Net and written following code. However I'm not getting any response but StatusCode: 404. Could someone assist understanding where I'm going wrong?

Also I'd like to understand, how do set Body in following code.

var httpClient = new HttpClient
{
   BaseAddress = new Uri("https://testURL.com"),
   Timeout = TimeSpan.FromMinutes(10)
};
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("audio/wav"));
httpClient.DefaultRequestHeaders.Add("Authorization", "Basic ldjfdljfdlfjdsjfdsl");

var content = new FormUrlEncodedContent(new[]
{
   new KeyValuePair<string, string>("model", "Test"),
});
var result = httpClient.PostAsync("api/v1/recognize", content).Result;

Here is what I'm doing in Postman and it works:

参数

身体

"Params" in Postman refers to query parameters which are appended to the URL. You'll see that the URL in Postman contains the parameters you added in the "Params" tab:

Postman URL 和查询参数

However, it seems those are just dummy values you've entered so perhaps you don't need them? In any case, the way you add query parameters to the request for HttpClient is a little different as it needs to be added to the URL.

After that you also need to add the audio file as content to your request. At the moment you're setting the "Accept" header to "audio/wav" but you probably want to set the "Content-Type" header instead (or are you expecting a WAV file to be returned in the response too?).

As far as I can see this is what you're missing:

using (var httpClient = new HttpClient())
{
    httpClient.Timeout = TimeSpan.FromMinutes(10);
    // Set request headers
    httpClient.DefaultRequestHeaders.Add("Authorization", "Basic ldjfdljfdlfjdsjfdsl");

    // Set query parameters
    var uriBuilder = new UriBuilder("https://testURL.com/api/v1/recognize");
    uriBuilder.Query = "model=Test";


    // Build request body
    // Read bytes from the file being uploaded
    var fileBytes = File.ReadAllBytes(wavFilePath);
    // Create request content with metadata/headers to tell the
    // backend which type of data (media type) is being uploaded
    var byteArrayContent = new ByteArrayContent(fileBytes);
    byteArrayContent.Headers.ContentType = MediaTypeHeaderValue.Parse("audio/wav");
    // Wrap/encode the content as "multipart/form-data"
    // See example of how the output/request looks here:
    // https://dotnetfiddle.net/qDMwFh
    var requestContent = new MultipartFormDataContent
    {
        {byteArrayContent, "audio", "filename.wav"}
    };

    var response = await httpClient.PostAsync(uriBuilder.Uri, requestContent);
}

I haven't tested this of course against your application, but it should be something along the lines of this. It might be that the backend doesn't expect "multipart/form-data" and just needs the "audio/wav". I can't see the output headers in your Postman screenshots, but if so, you can use byteArrayContent directly instead of wrapping it in MultipartFormDataContent .

Note: Don't use httpClient.PostAsync(...).Result . If you want to use the asynchronous method, you should await it. Depending on your code, using Result might give you problems if you're not careful. And remember to dispose the HttpClient after use (easiest solution is to use a using statement). If you plan on reusing the HttpClient for more requests, you can avoid disposing it until you're done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM