简体   繁体   English

NET Core (C#) 中的 POST 请求从 python 到 C#

[英]POST request in NET Core (C#) from python to C#

import requests

requests.post('https://dathost.net/api/0.1/game-servers/54f55784ced9b10646653aa9/start',
              auth=('john@doe.com', 'secretPassword'))

How would one write this in C#?如何在 C# 中编写这个? (NET Core) (NET 核心)

Apart of the added comments, I would recommend using a library called RestSharp .除了添加的评论外,我建议使用名为RestSharp的库。 You can easily find the nuget package and the code will be as easier as:你可以很容易地找到 nuget 包,代码会更简单:

var client = new RestClient("https://dathost.net");
client.Authenticator = new HttpBasicAuthenticator("john@doe.com", "secretPassword");

var request = new RestRequest("api/0.1/game-servers/{id}/start", Method.POST);
request.AddUrlSegment("id", "54f55784ced9b10646653aa9");

// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content;

You can also do async requests:您还可以执行异步请求:

client.ExecuteAsync(request, response => {
    Console.WriteLine(response.Content);
});

You can do it with HttpClient.您可以使用 HttpClient 来完成。

Add usings top of your code first.首先添加 using 顶部的代码。

using System.Net.Http;
using System.Net.Http.Headers;

And run this code wherever you want.并在您想要的任何地方运行此代码。

    var client = new HttpClient();
    var byteArray = Encoding.ASCII.GetBytes("john@doe.com:secretPassword");
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

    var response = await client.PostAsync(
        "https://dathost.net/api/0.1/game-servers/54f55784ced9b10646653aa9/start", null);

Hope this helps.希望这可以帮助。

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

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