在 C# 中调用 api 时出现 HttpResponseMessage returns 404

HttpReponseMessage returns 404 when making call to api in C#

我正在尝试遵循这些准则来调用他们的 API 并在 return 中获取预填充的 QR 码。

https://developer.swish.nu/api/qr-codes/v1#pre-filled-qr-code

但是我收到错误 404 未找到,这是我的代码:

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://mpc.getswish.net/qrg-swish");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));

var json = new {
payee = new {value = "1234", editable = false}, 
amount = new {value = 100, editable = false},
message = new {value = "test message", editable = false},
format = "png"
};
HttpResponseMessage response = await client.PostAsJsonAsync(
"/api/v1/prefilled", json);

有人知道我可能做错了什么吗?

client.BaseAddress = new Uri("https://mpc.getswish.net/qrg-swish");
HttpResponseMessage response = await client.PostAsJsonAsync("/api/v1/prefilled", json);

问题是传递给 PostAsJsonAsync 的路径中的前导 /,而 BaseAddress 中缺少尾随 /。将其更改为:

client.BaseAddress = new Uri("https://mpc.getswish.net/qrg-swish/");
HttpResponseMessage response = await client.PostAsJsonAsync("api/v1/prefilled", json);

HttpClient 通过执行 new Uri(BaseAddress, path)see here.

将传递给 PostAsJsonAsync 的路径与 HttpClient.BaseAddress 的值组合起来

如果我们试试这个:

var baseUri = new Uri("https://mpc.getswish.net/qrg-swish");
var result = new Uri(baseUri, "/api/v1/prefilled");
Console.WriteLine(result);

我们得到结果:

https://mpc.getswish.net/api/v1/prefilled

查看 Remarks for new Uri(Uri baseUri, string relativeUri),我们看到:

If the baseUri has relative parts (like /api), then the relative part must be terminated with a slash, (like /api/), if the relative part of baseUri is to be preserved in the constructed Uri.

Additionally, if the relativeUri begins with a slash, then it will replace any relative part of the baseUri

所以为了保留BaseAddress结尾的路径,需要以/结尾,传递给PostAsJsonAsync的路径需要不是/开头。


有了它,我们得到了 400 Bad Request 而不是 404 Not Found。让我们看一下响应主体,看看服务器是否告诉我们任何有用的信息:

HttpResponseMessage response = await client.PostAsJsonAsync(
            "api/v1/prefilled", json);
Console.WriteLine(response.StatusCode);
Console.WriteLine(await response.Content.ReadAsStringAsync());

我们得到:

BadRequest
{"timestamp":"2022-03-09T10:14:45.292+0000","status":400,"error":"Bad Request","message":"Invalid phone number length","path":"/qrg-swish/api/v1/prefilled"}

因此,我们的 phone 号码无效:它太短了。让我们解决这个问题:

payee = new {value = "01234567890", editable = false}, 

现在我们得到:

BadRequest
{"timestamp":"2022-03-09T10:15:30.675+0000","status":400,"error":"Bad Request","message":"The size parameter is required when using format PNG","path":"/qrg-swish/api/v1/prefilled"}

对了,我们需要指定一个尺寸。公平地说,文档确实说:

Size of the QR code. The code is a square, so width and height are the same. Not required if the format is svg.

所以让我们这样做:

size = 300,

到此为止,成功!