简体   繁体   English

如何使用凭据在 C# + WCF 中调用外部 API

[英]How to call external API in C# + WCF with credentials

I am trying to call external API with request for which I have an URL with credentials.我正在尝试使用具有凭据的 URL 的请求调用外部 API。

The external API is not accessible from browsers.无法从浏览器访问外部 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());
            }

I want to call external API by sending an object as a request from my c# code.我想通过从我的 c# 代码发送一个对象作为请求来调用外部 API。 The API is authenticated. API 已通过身份验证。

If you use webrequest or HttpClient,you could write as follows to send an object to the server.(assume your code about authenticating is right)如果你使用 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);
        }

The result.结果。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM