【问题标题】:How to call external API in C# + WCF with credentials如何在 C# + WCF 中使用凭据调用外部 API
【发布时间】:2019-01-03 04:57:55
【问题描述】:

我正在尝试使用具有凭据的 URL 的请求调用外部 API。

无法从浏览器访问外部 API。

string url = "https://ICSTESTQSic-tkmdlms.integration.ocp.oraclecloud.com:443/ic/api/integration/v1/flows/rest/TSA2ELOQUA_NURTURELEADS/1.0/NurturingLead";
        using (var client = new WebClient())
        {
            NetworkCredential credentials = new NetworkCredential("Username", "Password");
            client.Credentials = credentials;
            CredentialCache cc = new CredentialCache();
            cc.Add(
                new Uri(url),
                "Basic",
                new NetworkCredential("Username", "Password"));
            client.Credentials = cc;            

            using (Stream stream = client.OpenRead(url))
            using (StreamReader reader = new StreamReader(stream))
            {
                MessageBox.Show(reader.ReadToEnd());
            }

我想通过从我的 c# 代码发送一个对象作为请求来调用外部 API。 API 已通过身份验证。

【问题讨论】:

  • URL 不是 API。添加单词 REST 仅给出 API 的模糊形状,指定允许的 HTTP 动词。

标签: c# .net rest api wcf


【解决方案1】:

如果你使用 webrequest 或 HttpClient,你可以写如下向服务器发送一个对象。(假设你的验证代码是正确的)

WebRequest request = WebRequest.Create("http://localhost:60956/api/values");


        YClass yClass = new YClass() { Completion = 5, Message = "AA", Result = "Result" };
        JavaScriptSerializer serialize = new JavaScriptSerializer(); // the object is used to serialize the data , you could use any object that could serialize data
        byte[] objectContent = Encoding.UTF8.GetBytes(serialize.Serialize(yClass));
        request.ContentLength = objectContent.Length;
        request.ContentType = "application/json";
        request.Method = "POST";
        using (var stream = request.GetRequestStream())
        {
            stream.Write(objectContent, 0, objectContent.Length);
            stream.Close();
        }


        var resp = request.GetResponse();
        using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
        {
            string s = sr.ReadToEnd();
            System.Console.WriteLine(s);
        }

结果。

【讨论】:

  • 我使用了你的方法,但是在获取流时出现错误。错误是:-“底层连接已关闭。发送时发生意外错误。”
  • 你可以参考下面的链接,它结合了发布对象和发送证书到服务器,这里它使用 content-type application/x-www-form-urlencoded 来发送一个发布请求,如果你的内容-type为application-json,请使用jsonhttps://stackoverflow.com/questions/39528973/force-httpwebrequest-to-send-client-certificate
  • 感谢您的回复。我能够发送请求,但在这行代码“HttpWebResponse response = (HttpWebResponse)request.GetResponse()”上得到相同的错误“底层连接已关闭”。我正在使用 .NET 4.0。你能帮我解决这个问题吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多