【问题标题】:How to get the url response values in Asp.NET如何在 Asp.NET 中获取 url 响应值
【发布时间】:2012-04-11 01:32:06
【问题描述】:

我几乎敢问,但是我如何才能得到一个 URL 的响应数据呢? 就是想不起来了。

我的场景:我正在使用 twitter API 来获取用户的个人资料图片。该 API URL 返回 JPEG 位置。 所以如果我真的在我的视图中编写这个 HTML:

<img src="https://api.twitter.com/1/users/profile_image?screen_name=twitterapi&size=bigger"/> 

浏览器自动将响应 JPEG 用于 SRC 属性。像这样:

现在我的问题很简单:我怎样才能将 C# 中的 .jpg 位置放入我的数据库中?

【问题讨论】:

  • 你为什么敢 :) ..这是一个非常有趣的问题!

标签: c# asp.net twitter


【解决方案1】:

我不确定你在问什么。

我认为您可以在 c# 中使用WebClient.DownloadData 来调用该网址。下载文件后,您可以将其放入数据库中。

byte[] response = new System.Net.WebClient().DownloadData(url);

Download a file over HTTP into a byte array in C#?

编辑:这对我有用

WebRequest request = WebRequest.Create("https://api.twitter.com/1/users/profile_image?screen_name=twitterapi&size=bigger");
WebResponse response = request.GetResponse();
Console.WriteLine(response.ResponseUri);

Console.Read( );

来自A way to figure out redirection URL

编辑:这是我认为的另一种方法...使用来自 Read the absolute redirected SRC attribute URL for an image 的 show.json

http://api.twitter.com/1/users/show.json?screen_name=twitterapi

【讨论】:

  • 感谢您的回复。但是字节数据并不是真正需要的。通过调用 API url,twitter 会返回 profilepicture 的位置。如果您在浏览器中发布 url 'api.twitter.com/1/users/…',您可以对其进行测试。我想存储 Twitter API 返回的 jpg 位置
【解决方案2】:

您也可以使用 HttpClient 来完成:

public class UriFetcher
{
    public Uri Get(string apiUri)
    {
        using (var httpClient = new HttpClient())
        {
            var httpResponseMessage = httpClient.GetAsync(apiUri).Result;
            return httpResponseMessage.RequestMessage.RequestUri;
        }
    }
}

[TestFixture]
public class UriFetcherTester
{
    [Test]
    public void Get()
    {
        var uriFetcher = new UriFetcher();
        var fetchedUri = uriFetcher.Get("https://api.twitter.com/1/users/profile_image?screen_name=twitterapi&size=bigger");
        Console.WriteLine(fetchedUri);
    }
}

【讨论】:

  • 不错的答案; +1 简单示例和测试:-)
  • 感谢您的回答,但我对 Timmerz 代码感觉更舒服。很满意,所以点赞。
  • 注意:您需要使用 System.Net.Http - .net framework 4.5 或更高版本。
【解决方案3】:

您可以使用 HttpWebRequest 和 HttpWebResponse 类(通过using System.Net)来实现这一点;

  HttpWebRequest webRequest =
    WebRequest.Create("https://api.twitter.com/1/users/profile_image?screen_name=twitterapi&size=bigger") as HttpWebRequest;

  webRequest.Credentials = CredentialCache.DefaultCredentials;

  HttpWebResponse response = webRequest.GetResponse() as HttpWebResponse;

  string url = response.ResponseUri.OriginalString;

url 现在包含字符串"https://si0.twimg.com/profile_images/1438634086/avatar_bigger.png"

【讨论】:

    猜你喜欢
    • 2011-12-24
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 2022-08-11
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多