2.2携带请求数据
在获取第三方 API 数据时,通常需要携带请求数据,这些数据可以是 URL 地址参数或请求内容。最常见的做法是通过 URL 地址传递参数,以及发送 JSON 格式的数据。
在获取第三方 API 数据时,通常需要携带请求数据,这些数据可以是 URL 地址参数或请求内容。最常见的做法是通过 URL 地址传递参数,以及发送 JSON 格式的数据。
var content = await httpRemoteService.PostAsAsync<YourRemoteModel>("https://localhost:7044/HttpRemote/AddModel", builder => builder .WithQueryParameters(new { query1 = 1, query2 = "furion" }) // 设置 URL 查询参数 .SetJsonContent(new { id = 1, name = "furion" })); // 设置请求的 JSON 内容除了上述方式,还支持以下几种方法:
// 使用构建器模式var content = await httpRemoteService.SendAsAsync<YourRemoteModel>(HttpRequestBuilder.Post("https://localhost:7044/HttpRemote/AddModel") .WithQueryParameter("query1", 1) // 设置查询参数(支持单个设置) .WithQueryParameter("query2", "furion") // 设置查询参数(支持单个设置) .SetJsonContent("{\"id\":1,\"name\":\"furion\"}")); // 设置请求内容(支持直接传入 JSON 字符串)// 更多详细用法可参考第 19.2.1 节此外,您还可以使用 SetContent 方法来设置请求内容,该方法支持设置任意类型的请求内容。事实上,SetJsonContent 方法内部也是通过调用 SetContent 来实现的。
// 自定义 Content-Typevar content = await httpRemoteService.PostAsAsync<YourRemoteModel>("https://localhost:7044/HttpRemote/AddModel", builder => builder .WithQueryParameters(new { query1 = 1, query2 = "furion" }) // 设置查询参数 .SetContent(new { id = 1, name = "furion" }, "application/json")); // 设置请求内容// 自定义 Content-Type 支持配置 Charsetvar content = await httpRemoteService.PostAsAsync<YourRemoteModel>("https://localhost:7044/HttpRemote/AddModel", builder => builder .WithQueryParameters(new { query1 = 1, query2 = "furion" }) // 设置查询参数 .SetContent(new { id = 1, name = "furion" }, "application/json;charset=utf-8")); // 设置请求内容// 自定义 Content-Type 支持配置请求编码var content = await httpRemoteService.PostAsAsync<YourRemoteModel>("https://localhost:7044/HttpRemote/AddModel", builder => builder .WithQueryParameters(new { query1 = 1, query2 = "furion" }) // 设置查询参数 .SetContent(new { id = 1, name = "furion" }, "application/json;charset=utf-8", Encoding.UTF8)); // 设置请求内容