简体   繁体   English

C# 中的 API 调用 - 使用用户名和密码获取调用

[英]API call in C# - Get call using username and password

I've never had to do an API call before and I've been trying but so far unsuccessful and I think getting myself even more confused :/ .我以前从来没有做过 API 调用,我一直在尝试,但到目前为止没有成功,我认为让自己更加困惑:/。

Basically what I'm trying to do is a get call passing in a username to get back the SYSID of the user, then using the SYSID in a post call to create a support ticket for the user.基本上我想要做的是一个 get 调用,传入一个用户名来取回用户的 SYSID,然后在后调用中使用 SYSID 为用户创建一个支持票。 Service now is the ticketing system being used服务现在是正在使用的票务系统

I have managed to successfully do it in powershell using the sample code provided with some slight modifications as below:我已经使用提供的示例代码在 powershell 中成功地做到了这一点,并进行了一些细微的修改,如下所示:

$user = "TestLogin"
$pass = "TestPassword"
$QueryUser = "TestUser"
$description = "Test description"
$title = "Test title"

# Build auth header
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user, $pass)))

# Set proper headers
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add('Authorization',('Basic {0}' -f $base64AuthInfo))
$headers.Add('Accept','application/json')

# Specify endpoint uri
$uri = "https://TestURL.com/api/Test/table/sys_user?sysparm_query=user_name=" + $QueryUser + "&sysparm_fields=sys_id"
# Specify HTTP method
$method = "get"

{request.body ? "$body = \"" :"""}

# Send HTTP request
$response = Invoke-WebRequest -Headers $headers -Method $method -Uri $uri

#Removes {"result":[{"sys_id":" off the start of the response string
$response = $response -replace ".*"":"""
#Removes "}]} off the end of the response string
$SYSID = $response -replace """}]}*."

# Print response
write-host $SYSID


# Set proper headers
$headers.Add('Content-Type','application/json')

# Specify endpoint uri
$uri = "https://TestURL.com/api/Test/table/new_call"

# Specify HTTP method
$method = "post"

# Specify request body
$body = @{
            caller= $SYSID
            description= $description
            short_description= $title + " - " + $QueryUser
         }
$bodyJson = $body | ConvertTo-Json

# Send HTTP request
$response = Invoke-WebRequest -Headers $headers -Method $method -Uri $uri -Body $bodyJson

# Print response
$response.RawContent

The latest code I've used is below followed by the error I'm getting (some of it is commented out but that was just me trying different things to try get it to function) This portion is just the get call: (Note: the below is just the get portion, I havent really tried the post yet to create the ticket)下面是我使用的最新代码,然后是我得到的错误(其中一些被注释掉了,但这只是我尝试不同的事情来尝试使其正常运行)这部分只是 get 调用:(注意:以下只是获取部分,我还没有真正尝试过该帖子来创建票证)

public string Get(string QueryUsername)
        {    

    string username = "TestLogin";
    string password = "TestPassword";
    string url = "https://TestURL.com/api/Test/table/sys_user?sysparm_query=user_name=" + QueryUsername + "&sysparm_fields=sys_id";

    var auth = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password));
    HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
    request.Headers.Add("Authorization", auth);
    string method = "get";
    string SYSID = "";

    //using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    //{
    //    string json = JsonConvert.SerializeObject(new
    //    {
    //        User_name = QueryUsername
    //    });

    //    streamWriter.Write(json);
    //}

    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
    {
        var res = new StreamReader(response.GetResponseStream()).ReadToEnd();

        JObject joResponse = JObject.Parse(res.ToString());
        JObject ojObject = (JObject)joResponse["result"];
        string callNumber = ((JValue)ojObject.SelectToken("number")).Value.ToString();

        return (res.ToString());
    };
}

Current error:当前错误:

System.InvalidCastException: 'Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'Newtonsoft.Json.Linq.JObject'.' System.InvalidCastException: '无法将类型为'Newtonsoft.Json.Linq.JArray'的对象转换为类型'Newtonsoft.Json.Linq.JObject'。

Error is occuring at line 53:第 53 行出现错误:

JObject ojObject = (JObject)joResponse["result"]; JObject ojObject = (JObject)joResponse["result"];

Debugger output of variables:变量的调试器输出: 在此处输入图片说明

I've been trying and reading watching tutorials but have not really progressed and decided it's time to reach out for some help.我一直在尝试和阅读教程,但并没有真正取得进展,我决定是时候寻求帮助了。

Any assistance or links to tutorials that might help me out would be greatly appreciated任何可能对我有帮助的帮助或教程链接将不胜感激

Trying to make a class and deserialize it using尝试创建一个类并使用反序列化它

public class Result
{
     public string Number {get; set;}
     .
     .
     .
}

.
.
.

//in your "Get" method change the return for the class type
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
    var res = new StreamReader(response.GetResponseStream()).ReadToEnd();

    return JsonConvert.DeserializeObject<Result>(res);
};

.
.
.

//if you need to get 'callNumber'
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
    var res = new StreamReader(response.GetResponseStream()).ReadToEnd();

    var obj = JsonConvert.DeserializeObject<Result>(res);

    var callNumber = obj.Number;

    return obj;
};

If your response looks something like follows如果您的回复如下所示

{
   ....,
   ....,

   "result":
   {
      "number": 001230123,
      ....
      ....
   },

   ....
   ....
}

The following code will work.以下代码将起作用。

using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    {
        var res = new StreamReader(response.GetResponseStream()).ReadToEnd();
        var dataObj = JsonConvert.DeserializeObject<dynamic>(res.ToString());

        try
        {
            var resultObj = dataObj["result"].Value;
            string callNumber = resultObj["number"].Value.ToString();
        }
        catch
        {
            // Handle your exceptions here
        }

        return (res.ToString());
    }
};

Below is the code that I've managed toget working to return just the number from the JSON response下面是我设法从 JSON 响应中返回数字的代码

public class Result
    {
        public string sys_id { get; set; }
    }

    public class RootObject
    {
        public List<Result> result { get; set; }
    }




using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {

                var res = new StreamReader(response.GetResponseStream()).ReadToEnd();
                RootObject datalist = JsonConvert.DeserializeObject<RootObject>(res);

                if (datalist.result != null && datalist.result.Count > 0)
                {
                    var data = datalist.result[0];
                    UserSysID = "";
                    UserSysID = data.sys_id;
                    return data.sys_id;
                }
                return null;
            }
        }

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

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