我正在 retrofit 一个应用程序以使用 PHP HTTP 代理(用于缓存)而不是实际的 API 服务器,该应用程序当前将服务器 URI 和路径与代码结合在一起:
methodUri = new Uri(apiUri, method.Path)
地点:
- apiUri = "http://api.eve-online.com/ "(System.Uri 对象)
- method.Path = "/char/SkillIntraining.xml.aspx"(字符串)
上面语句的结果是
"http://api.eve-online.com/char/SkillIntraining.xml.aspx" (System.Uri Object)
要使用 PHP HTTP 代理,必须按如下方式更改请求
- apiUri = "http://www.r-s.co.uk/eproxy.php "(System.Uri 对象)
- method.Path = "/char/SkillIntraining.xml.aspx"(字符串)
我期望的输出是:
"http://www.r-s.co.uk/eproxy.php/char/SkillIntraining.xml.aspx" (System.Uri Object)
但是我得到的输出是:
"http://www.r-s.co.uk/char/SkillIntraining.xml.aspx" (System.Uri Object)
我知道这是构造函数 Uri(Uri, string) 的正确功能,我的问题是用什么更好的函数或构造函数代替它来获得我期望的输出?我尝试删除 method.Path 中的前导“/”,将其从绝对路径转换为相对路径,但这没有帮助。
注意:下面的两种解决方案都有效,但是 System.UriBuilder 提供了一种更强大的机制来组合 URI 和路径,在我的例子中导致的更改更少资源而不是使用 System.Uri。如果我可以选择,我会将两个答案都标记为正确。
最佳答案
不要使用 Uri 对象,使用 UriBuilder - 它可以更好地处理缺少的斜杠
所以
Uri apiUri = new Uri("http://www.r-s.co.uk/eproxy.php");
string methodPath = "/char/SkillIntraining.xml.aspx";
System.UriBuilder uriBuilder = new System.UriBuilder(apiUri);
uriBuilder.Path += methodPath;
Console.WriteLine(uriBuilder.Uri.ToString());
按预期工作并生成 http://www.r-s.co.uk/eproxy.php/char/SkillIntraining.xml.aspx
关于c# - 组合 URI 和路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/679171/