远程服务器返回错误:(400)错误请求C#

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

我已经创建了调用API的应用程序,其中一些要求就像apikey,username。但是我得到了这个错误

远程服务器返回错误:(400)错误请求

以下是我的代码

public void Send(string method, string uri)
{
    var nonce = GetRandomString(32);
    var timestamp = DateTime.UtcNow.ToString("o");
    var passwordDigest = System.Convert.ToBase64String(Encoding.UTF8.GetBytes(Sha1(nonce + timestamp + secret)));
    var authHeader = String.Format("Username=\"{0}\", PasswordDigest=\"{1}\", Nonce=\"{2}\", Created=\"{3}\"  Content-type: application/json;charset=\"utf-8\"", key, passwordDigest, nonce, timestamp);

    var httpRequest = (HttpWebRequest)WebRequest.Create(uri);
    httpRequest.Method = method;
    httpRequest.Headers.Add("X-WSSE: USERNAME " + authHeader);

    if (method.Equals("POST"))
    {
        try
        {
            var serializer = new JavaScriptSerializer();
            var data = new
            {
                name = "testing",
                key_id = "3",
                external_ids = external_ids
            };
            var json = serializer.Serialize(data);
            Byte[] byteArray = Encoding.UTF8.GetBytes(json);
            httpRequest.ContentLength = byteArray.Length;
            Stream dataStream = httpRequest.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            WebResponse tResponse = httpRequest.GetResponse();

            dataStream = tResponse.GetResponseStream();

            StreamReader tReader = new StreamReader(dataStream);

            String sResponseFromServer = tReader.ReadToEnd();
            tReader.Close();
            dataStream.Close();
            tResponse.Close();
        }catch(Exception ex){
            ex.Message.ToString();
        }
    }
c# .net rest httpwebrequest
1个回答
0
投票

根据文档,以下行:

httpRequest.Headers.Add("X-WSSE: USERNAME " + authHeader);

应该:

httpRequest.Headers.Add("X-WSSE: UsernameToken " + authHeader);

看来你复制和粘贴不正确或其他东西。

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