[英]HttpGet with parameters using HttpWebResponse C#
我正在嘗試使用添加的參數執行GET。 我以前使用的WebClient代碼突然停止工作,因此我決定切換為使用HttpWebRequest / HttpWebResponse。 您如何正確添加參數? 我有一個帶有兩個字符串參數的REST函數,但是我看不到它們。 基本上,如何將多個參數添加到GET調用中?
這是我的GET代碼(booksString是以逗號分隔的book 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軟件包,該軟件包非常簡潔地封裝了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}&param2 = {1}
使用string.format填充值並進行調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.