python到c#(关于服务器请求)

2024-05-16 09:52:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要把这个python代码翻译成C#:

messages = { "to" :"PhoneNumber" }
body = {
    "type" : "SMS",
    "contentType" : "COMM",
    "from" : "PhoneNumber2",
    "subject" :"subject",
    "content" : "Hell world",
    "messages" : [messages]
}
body2 = json.dumps(body)
headers = {
    'Content-Type': 'application/json; charset=utf-8',
    'X-ncp-apigw-timestamp': timestamp,
    'x-ncp-iam-access-key': access_key,
    'x-ncp-apigw-signature-v2': make_signature(uri, access_key)
    }

res = requests.post(apiUrl, headers=headers, data=body2)

res.request
res.status_code
res.raise_for_status()

print(res.json())

所以我试着:

    public class themessage
    {
        public string to;
    }
    public class body
    {
        public string type;
        public string contentType;
        public string from;
        public string subject;
        public string content;
        public themessage messages;
    }


            var obj = new body
            {
                type = "SMS",
                contentType = "COMM",
                from = "PN",
                subject = "subject",
                content = "Hell World",
                messages = new themessage
                {
                    to = "PN"
                }
            };


            var client = new RestClient(apiUrl);
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json; charset=utf-8");
            request.AddHeader("X-ncp-apigw-timestamp", timestamp);
            request.AddHeader("x-ncp-iam-access-key", accessKey);
            request.AddHeader("x-ncp-apigw-signature-v2", test);
            request.AddJsonBody(obj); // **this is where I'm concerning part**
            IRestResponse response = client.Execute(request);

但是,如您所料,未能发布错误消息“Not requested format”something。你知道吗

我做JsonBody的时候有什么问题吗?或过帐流程?你知道吗

感谢您提前给出所有答案!你知道吗


Tags: keyjsonnewstringaccessrequestbodyres
1条回答
网友
1楼 · 发布于 2024-05-16 09:52:41

在我上次对IRestRequest interface的评论之后,您的类层次结构应该类似于

public class themessage
{
    public string to;
}

public class body
{
    public string type;
    public string contentType;
    public string from;
    public string subject;
    public string content;
    public themessage[] messages; // <- Array here
}

你用它创建的对象

var obj = new body
{
    type = "SMS",
    contentType = "COMM",
    from = "PN",
    subject = "subject",
    content = "Hell World",
    messages = new themessage[] { new themessage{to = "PN"} }
};

RestClientRestRquest的代码保持原样。你知道吗

相关问题 更多 >