使用 HttpWebResponse C# 带参数的 HttpGet
HttpGet with parameters using HttpWebResponse C#
我正在尝试使用添加的参数执行 GET。我之前使用的 WebClient 代码突然停止工作,所以我决定改用 HttpWebRequest/HttpWebResponse。您如何正确添加参数?我有一个接受两个字符串参数的 REST 函数,但我看不到它们。基本上,如何向 GET 调用添加多个参数?
这是我的 GET 代码(booksString 是以逗号分隔的图书 ID 字符串):
string webAddress = "http://localhost:5000/stuff/address";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webAddress);
request.Headers.Add("bookIds", booksString);
request.Method = "GET";
request.Accept = "text/html";
request.KeepAlive = true;
request.ProtocolVersion = HttpVersion.Version10;
string text = "";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(),
Encoding.ASCII))
{
text = reader.ReadToEnd();
}
}
Console.WriteLine("text: " + text);
这是我的 REST 代码:
public List<Book> GetBooks(string bookIds, string param2)
{
Console.WriteLine("book IDs: " + bookIds + " " + param2);
}
每当我运行这个代码bookIds
是空的?如何发送多个参数并让我的 REST 函数识别数据?
尝试使用RestSharp Nuget Package,它把HTTPWeb Request封装得非常整齐
因为你可以做到这一点
var baseUrl = "http://localhost:5000/";
var resource = "stuff/address";
var api = new RestClient(baseUrl);
var request = new RestRequest(resource, Method.GET);
request.AddQueryParameter("bookIds", bookString);
request.AddQueryParameter("param2", value);
api.Execute(request);
尝试使用 URL 编码。
http://localhost:5000/stuff/address?bookIds={0}¶m2={1}
使用string.format填写值并拨打电话。
我正在尝试使用添加的参数执行 GET。我之前使用的 WebClient 代码突然停止工作,所以我决定改用 HttpWebRequest/HttpWebResponse。您如何正确添加参数?我有一个接受两个字符串参数的 REST 函数,但我看不到它们。基本上,如何向 GET 调用添加多个参数?
这是我的 GET 代码(booksString 是以逗号分隔的图书 ID 字符串):
string webAddress = "http://localhost:5000/stuff/address";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webAddress);
request.Headers.Add("bookIds", booksString);
request.Method = "GET";
request.Accept = "text/html";
request.KeepAlive = true;
request.ProtocolVersion = HttpVersion.Version10;
string text = "";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(),
Encoding.ASCII))
{
text = reader.ReadToEnd();
}
}
Console.WriteLine("text: " + text);
这是我的 REST 代码:
public List<Book> GetBooks(string bookIds, string param2)
{
Console.WriteLine("book IDs: " + bookIds + " " + param2);
}
每当我运行这个代码bookIds
是空的?如何发送多个参数并让我的 REST 函数识别数据?
尝试使用RestSharp Nuget Package,它把HTTPWeb Request封装得非常整齐
因为你可以做到这一点
var baseUrl = "http://localhost:5000/";
var resource = "stuff/address";
var api = new RestClient(baseUrl);
var request = new RestRequest(resource, Method.GET);
request.AddQueryParameter("bookIds", bookString);
request.AddQueryParameter("param2", value);
api.Execute(request);
尝试使用 URL 编码。
http://localhost:5000/stuff/address?bookIds={0}¶m2={1}
使用string.format填写值并拨打电话。