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

问题描述 投票:0回答:1

我正在尝试通过请求调用外部 API,我有一个带有凭据的 URL。

外部 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已通过身份验证。

c# .net rest wcf
1个回答
0
投票

如果你使用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);
        }

结果。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.