gpt4 book ai didi

c# - 使用 http 客户端 API 构建 URI

转载 作者:行者123 更新时间:2023-11-30 20:55:26 24 4
gpt4 key购买 nike

我必须使用动态查询字符串构建一个 URI 地址,并寻找一种通过代码构建它们的舒适方法。

我浏览了 System.Net.Http 程序集,但没有找到适合这种情况的类或方法。这个API不提供这个吗?我在 StackOverflow 的搜索结果使用了 System.Web 中的 HttpUtility 类,但我不想在我的类库中引用任何 ASP.Net 组件。

我需要这样的 URI:http://www.myBase.com/get?a=1&b=c .

在此先感谢您的帮助!

更新(2013/9/8):

我的解决方案是创建一个 URI 构建器,它使用 System.Net.WebUtilitiy 类对值进行编码(不幸的是,导入的 NuGet 包没有提供强名称键)。这是我的代码:

/// <summary>
/// Helper class for creating a URI with query string parameter.
/// </summary>
internal class UrlBuilder
{
private StringBuilder UrlStringBuilder { get; set; }
private bool FirstParameter { get; set; }

/// <summary>
/// Creates an instance of the UriBuilder
/// </summary>
/// <param name="baseUrl">the base address (e.g: http://localhost:12345)</param>
public UrlBuilder(string baseUrl)
{
UrlStringBuilder = new StringBuilder(baseUrl);
FirstParameter = true;
}

/// <summary>
/// Adds a new parameter to the URI
/// </summary>
/// <param name="key">the key </param>
/// <param name="value">the value</param>
/// <remarks>
/// The value will be converted to a url valid coding.
/// </remarks>
public void AddParameter(string key, string value)
{
string urlEncodeValue = WebUtility.UrlEncode(value);

if (FirstParameter)
{
UrlStringBuilder.AppendFormat("?{0}={1}", key, urlEncodeValue);
FirstParameter = false;
}
else
{
UrlStringBuilder.AppendFormat("&{0}={1}", key, urlEncodeValue);
}

}

/// <summary>
/// Gets the URI with all previously added paraemter
/// </summary>
/// <returns>the complete URI as a string</returns>
public string GetUrl()
{
return UrlStringBuilder.ToString();
}
}

希望这对 StackOverflow 的某些人有所帮助。我的请求有效。

比约恩

最佳答案

如果你依赖Tavis.Link你可以使用 URI Templates指定参数。

    [Fact]
public void SOQuestion18302092()
{
var link = new Link();
link.Target = new Uri("http://www.myBase.com/get{?a,b}");

link.SetParameter("a","1");
link.SetParameter("b", "c");

var request = link.CreateRequest();
Assert.Equal("http://www.myBase.com/get?a=1&b=c", request.RequestUri.OriginalString);


}

在 Github repo 上有更多关于您可以使用 Tavis.Link 做什么的示例.

关于c# - 使用 http 客户端 API 构建 URI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18302092/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com