如何在c#中使用给定的api键获取http内容

本文关键字:api 获取 内容 http | 更新日期: 2023-09-27 18:08:53

http://ssw.com/profile/?apikey = skdwkdkfkkdj

我试图使用

public async Task<string> GetFromUriAsync(string requestUri, string token)
    {
        var client = new HttpClient();
        client.BaseAddress = new Uri(BaseUri);
        client.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("apikey", "=" + token);
        HttpResponseMessage response = await client.GetAsync(requestUri);
        response.EnsureSuccessStatusCode();
        string responseBody = await response.Content.ReadAsStringAsync();
        return responseBody;
    }

则返回null

是我错过了什么还是完全错了?

谢谢

如何在c#中使用给定的api键获取http内容

您试图在HTTP请求的标头信息中传递API密钥。你需要做的就是传递整个URL,而不需要任何额外的头信息。

IE:使用"http://ssw.com/profile?apikey=abcdef"作为requestUri,发送令牌为空。另外,删除client.DefaultRequestHeaders.Authorization属性的设置。授权应该是一个用户/通行证系统,而不是一个基于令牌的系统。

要测试这一点,下载Fiddler 4 (https://www.telerik.com/download/fiddler)。一旦你安装了fiddler,在"Composer"选项卡上,你可以通过将URL直接放入URL框并单击"执行"来测试你需要的不同查询。然后,您将能够使用检查器来查看响应,并找出您需要从那里进行的操作。

下面是我用于HTTP GET和POST操作的类:
    public static string HTTPGET(string url)
    {
        try
        {
            HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
            request.Timeout = 100000;
            HttpWebResponse response = (HttpWebResponse) request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            if (responseStream != null)
                using (StreamReader resStream = new StreamReader(responseStream))
                    return resStream.ReadToEnd();
            return null;
        }
        catch (Exception e)
        {
            Console.WriteLine(url);
            Console.WriteLine(e);
            return null;
        }
    }
    public static string HTTPPOST(string url, string postData)
    {
        try
        {
            HttpWebRequest webRequest = (HttpWebRequest) WebRequest.Create(url);
            webRequest.Method = "POST";
            webRequest.ContentType = "x-www-form-urlencoded";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            using (Stream requestStream = webRequest.GetRequestStream())
                requestStream.Write(byteArray, 0, byteArray.Length);
            using (Stream responseStream = webRequest.GetResponse().GetResponseStream())
                if (responseStream != null)
                    using (StreamReader responseReader = new StreamReader(responseStream))
                        return responseReader.ReadToEnd();
            return null;
        }
        catch (Exception e)
        {
            Console.WriteLine(url);
            Console.WriteLine(postData);
            Console.WriteLine(e);
            return null;
        }
    }