问题描述
我需要发送此HTTP发布请求:
I need to send this HTTP Post Request:
POST https://webapi.com/baseurl/login
Content-Type: application/json
{"Password":"password",
"AppVersion":"1",
"AppComments":"",
"UserName":"username",
"AppKey":"dakey"
}
像上面一样,它在RestClient和PostMan中也很好用.
It works great in RestClient and PostMan just like above.
我需要以编程方式使用它,并且不确定是否要使用
I need to have this pro-grammatically and am not sure if to use
WebClient,HTTPRequest或WebRequest完成此操作.
WebClient, HTTPRequest or WebRequest to accomplish this.
问题在于如何设置正文内容的格式并将其与请求一起发送到上方.
The problem is how to format the Body Content and send it above with the request.
这是我使用WebClient示例代码的地方...
Here is where I am with example code for WebClient...
private static void Main(string[] args)
{
RunPostAsync();
}
static HttpClient client = new HttpClient();
private static void RunPostAsync(){
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
Inputs inputs = new Inputs();
inputs.Password = "pw";
inputs.AppVersion = "apv";
inputs.AppComments = "apc";
inputs.UserName = "user";
inputs.AppKey = "apk";
var res = client.PostAsync("https://baseuriplus", new StringContent(JsonConvert.SerializeObject(inputs)));
try
{
res.Result.EnsureSuccessStatusCode();
Console.WriteLine("Response " + res.Result.Content.ReadAsStringAsync().Result + Environment.NewLine);
}
catch (Exception ex)
{
Console.WriteLine("Error " + res + " Error " +
ex.ToString());
}
Console.WriteLine("Response: {0}", result);
}
public class Inputs
{
public string Password;
public string AppVersion;
public string AppComments;
public string UserName;
public string AppKey;
}
现在就可以使用(200)OK服务器和响应了
This DOES NOW WORK and responses with a (200) OK Server and Response
推荐答案
为什么要生成自己的json?
Why are you generating you own json?
使用JsonNewtonsoft的JSONConvert
.
Use JSONConvert
from JsonNewtonsoft.
您的json对象字符串值需要" "
引号和,
Your json object string values need " "
quotes and ,
我将使用http客户端进行发布,而不是使用webclient.
I'd use http client for Posting, not webclient.
using (var client = new HttpClient())
{
var res = client.PostAsync("YOUR URL",
new StringContent(JSONConvert.serializeObject(
new { OBJECT DEF HERE },
Encoding.UTF8, "application/json")
);
try
{
res.Result.EnsureSuccessStatusCode();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
这篇关于C#Web API在HTTP Post REST客户端中发送正文数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!