【问题标题】:How to consume 3rd party web services from the controller?如何从控制器使用 3rd 方 Web 服务?
【发布时间】:2014-02-03 00:57:36
【问题描述】:

我想从控制器中使用部分 Twitter API,这样我就可以在用户不启用 javascript 的情况下提供内容。

我计划创建一个代理控制器来管理 API uri 和身份验证令牌,但我不确定如何从后端进行实际的服务调用。我更愿意将返回的数据复制到实体对象中,以便在视图中轻松格式化它们。

是否有关于我需要使用的类集的示例或文档?

【问题讨论】:

  • 你是认真的问如何创建HTTP client in .NET吗?
  • 到目前为止,我只通过客户端使用 Web 服务。对不起。

标签: asp.net-mvc web-services


【解决方案1】:

如果你想创建一个网络请求,这是一个例子:

(pData可以是web api的参数)

    private string _callWebService(string pUrl, string pData)
    {
        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(pUrl);
            request.Method = "POST";
            request.ContentType = "...";
            byte[] bytes = Encoding.UTF8.GetBytes(pData);
            request.ContentLength = bytes.Length;

            using (var writer = request.GetRequestStream())
            {
                writer.Write(bytes, 0, bytes.Length);
            }

            using(var response = (HttpWebResponse)request.GetResponse())
            {
                 if (response.StatusCode.ToString().ToLower() == "ok")
                 {
                    using(var contentReader = new StreamReader(response.GetResponseStream()))
                    {
                        return contentReader.ReadToEnd();
                    }
                 }
             }
        }
        catch (Exception)
        {
            return string.Empty;
        }
        return string.Empty;
    }

【讨论】:

  • 非常感谢。我将使用它开始。
  • @JohnSaunders 感谢您的提醒。我更新了我的答案,现在可以吗? (例外情况,我使用Empty,因为这只是一个例子)
【解决方案2】:

您需要使用的实际代码如下,它验证并检索用户的时间线。

它来自我去年的问题,我在问题中提到的 Github 项目中有一个 MVC 项目的工作示例和一个 nuget 安装。您可以使用 nuget 包,也可以直接从 Github 复制代码。

Authenticate and request a user's timeline with Twitter API 1.1 oAuth

// You need to set your own keys and screen name
var oAuthConsumerKey = "superSecretKey";
var oAuthConsumerSecret = "superSecretSecret";
var oAuthUrl = "https://api.twitter.com/oauth2/token";
var screenname = "aScreenName";

// Do the Authenticate
var authHeaderFormat = "Basic {0}";

var authHeader = string.Format(authHeaderFormat,
    Convert.ToBase64String(Encoding.UTF8.GetBytes(Uri.EscapeDataString(oAuthConsumerKey) + ":" +
    Uri.EscapeDataString((oAuthConsumerSecret)))
));

var postBody = "grant_type=client_credentials";

HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(oAuthUrl);
authRequest.Headers.Add("Authorization", authHeader);
authRequest.Method = "POST";
authRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
authRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

using (Stream stream = authRequest.GetRequestStream())
{
    byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody);
    stream.Write(content, 0, content.Length);
}

authRequest.Headers.Add("Accept-Encoding", "gzip");

WebResponse authResponse = authRequest.GetResponse();
// deserialize into an object
TwitAuthenticateResponse twitAuthResponse;
using (authResponse)
{
    using (var reader = new StreamReader(authResponse.GetResponseStream())) {
        JavaScriptSerializer js = new JavaScriptSerializer();
        var objectText = reader.ReadToEnd();
        twitAuthResponse = JsonConvert.DeserializeObject<TwitAuthenticateResponse>(objectText);
    }
}

// Do the timeline
var timelineFormat = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={0}&include_rts=1&exclude_replies=1&count=5";
var timelineUrl = string.Format(timelineFormat, screenname);
HttpWebRequest timeLineRequest = (HttpWebRequest)WebRequest.Create(timelineUrl);
var timelineHeaderFormat = "{0} {1}";
timeLineRequest.Headers.Add("Authorization", string.Format(timelineHeaderFormat, twitAuthResponse.token_type, twitAuthResponse.access_token));
timeLineRequest.Method = "Get";
WebResponse timeLineResponse = timeLineRequest.GetResponse();
var timeLineJson = string.Empty;
using (timeLineResponse)
{
    using (var reader = new StreamReader(timeLineResponse.GetResponseStream()))
    {
         timeLineJson = reader.ReadToEnd();
    }
}


public class TwitAuthenticateResponse {
    public string token_type { get; set; }
    public string access_token { get; set; }
}

【讨论】:

猜你喜欢
  • 2017-03-07
  • 1970-01-01
  • 2014-05-25
  • 2013-06-12
  • 1970-01-01
  • 2014-03-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-05
相关资源
最近更新 更多