如何在C#中调用API时验证URL? [英] How to validate URL while calling an API in C# ?

查看:353
本文介绍了如何在C#中调用API时验证URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很擅长使用API​​。我在C#中调用了一个天气API。目前我正在使用UWP(通用Windows平台)制作天气应用程序。当我运行以下代码时。

I'm very new to consuming APIs. I'm calling a weather API in C#.Currently I'm making weather Application in UWP ( Universal Windows Platform ). When I run the following code .

var client = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get,
                    "api.openweathermap.org/data/2.5/weather?q=" + cityName + "," + countryName);
                var response = await client.SendAsync(request);
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var result = response.Content;
                    string restultString = await result.ReadAsStringAsync();
                    // var data = JsonConvert.
                    var data = JsonConvert.DeserializeObject<RootObject>(restultString);
                    lblWeatherResults.Text = data.sys.country.ToString() +" - "+ data.main.temp.ToString();
                }



我收到错误,要求我提供基本网址和/或绝对网址。我无法弄清楚为什么会出现这个错误。

这是我得到的错误。


I receive error which is asking me to provide base url and or absolute URL. I'm unable to figure out why this error coming.
this is the error i'm getting .

An Invalid request URL was provided. The ruquest URL must either be an absolute URL or BaseAddress must be set. 





这里是我的API我试图使用C#配置我的应用程序。



我尝试过:



我在Google上搜索它但找不到有用的资料。它要求正确的URL,但指定的URL格式这里与我正在尝试的完全相同。



here is the API which i'm trying to configure into my application using C#.

What I have tried:

I search it on Google but could't find useful material. It is asking for the correct URL but URL Format specified here is exactly the same which i'm trying .

推荐答案

您需要在请求中提供协议。尝试:

You need to provide the protocol in the request. Try:
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get,
    "http://api.openweathermap.org/data/2.5/weather?q=" + cityName + "," + countryName);


问题是'api.openweathermap.org/data/2.5/weather'是一个相对URI ...相对于你当前的地址......

你必须声明,这是绝对的一,购买定义它的根(原产地)......

在你的情况下它应该是'//api.openweathermap.org/data/2.5/weather'...
The problem is that 'api.openweathermap.org/data/2.5/weather' is a relative URI...Relative to you current address...
You have to state, that this is a absolute one, buy defining it's root (origin)...
In your case it should be '//api.openweathermap.org/data/2.5/weather'...


这篇关于如何在C#中调用API时验证URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆