如何为api调用组合url和字符串[重复]
Posted
技术标签:
【中文标题】如何为api调用组合url和字符串[重复]【英文标题】:How to combine url and string for api call [duplicate] 【发布时间】:2021-01-08 06:21:08 【问题描述】:我正在尝试在运行时组合一个 url 和字符串,然后调用它。
public static Uri Append(this Uri uri, params string[] paths)
return new Uri(paths.Aggregate(uri.AbsoluteUri, (current, path) => string.Format("0/1", current.TrimEnd('/'), path.TrimStart('/'))));
var url = new Uri("https://127.0.0.1:2999/liveclientdata/playerscores?summonerName=").Append(_PlayerName).AbsoluteUri;
但是当我调用它时,会返回此错误:
Failed the request: HTTP/1.1 400 Bad Request
网址是这样的
https://127.0.0.1:2999/liveclientdata/playerscores?summonerName=/%22KidKiwi91%22
我知道错误是由 url 和字符串的串联引起的,因为我将其全部设为一个 url,而不是在运行时将它们组合起来。
我尝试过的其他事情:
string url = "urlgoeshere=" + playername;
string url = UnityWebRequest.EscapeURL("urlgoeshere" + playername);
string url_q = "urlgoeshere=" + playername;
var url=new Uri(url_q);
使用 this 调用它
private IEnumerator GetJSON(string url, System.Action<string> callback)
failed = false;
//Debug.Log(url);
using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
webRequest.certificateHandler = new BypassCertificate();
yield return webRequest.SendWebRequest();
string error = webRequest.error;
if (error != null)
Debug.Log("Failed the request: " + error);
failed = true;
else
callback?.Invoke(webRequest.downloadHandler.text);
//Debug.Log(webRequest.downloadHandler.text);
有什么想法吗?
谢谢
【问题讨论】:
这能回答你的问题吗? Path.Combine for URLs? 不,我已经尝试了其中的一半,所有的错误都相同 您是否尝试过调试确切的最终 URL 并将其与您硬编码的有效 URL 进行比较?换句话说:您确定问题出在代码上还是您的网址根本不正确?400
表示服务器已正确访问,但不理解请求......您能否发布一个在硬编码时正常工作的 URL,并告诉我们您的所有变量到底包含什么?我很确定/
太多了,应该是https://127.0.0.1:2999/liveclientdata/playerscores?summonerName=%22KidKiwi91%22
@derHugo Working url: 127.0.0.1:2999/liveclientdata/… Concated url: 127.0.0.1:2999/liveclientdata/…" 看起来像是在添加引号
那可能是%22
.. 你的_PlayerName
到底长什么样?您可能可以通过使用_PlayerName.Trim('"')
来避免它(' " '
有点难以看到;))
【参考方案1】:
试试这个
string url_q = "https://127.0.0.1:2999/liveclientdata/playerscores?summonerName=" +
playername;
var url=new Uri(url_q);
【讨论】:
不幸的是同样的错误 请提供剩下的代码,你想把这个url放在哪里? 添加到原帖 你在 url 变量中得到了什么值?以上是关于如何为api调用组合url和字符串[重复]的主要内容,如果未能解决你的问题,请参考以下文章
如何为调用外部 API 的 Laravel Artisan 命令编写 PHPUnit 测试,而无需物理调用该 API?