下面是我使用的代码:
// create a request
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(url); request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
// turn our request string into a byte stream
byte[] postBytes = Encoding.UTF8.GetBytes(json);
// this is important - make sure you specify type this way
request.ContentType = "application/json; charset=UTF-8";
request.Accept = "application/json";
request.ContentLength = postBytes.Length;
request.CookieContainer = Cookies;
request.UserAgent = currentUserAgent;
Stream requestStream = request.GetRequestStream();
// now send it
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
// grab te response and print it out to the console along with the status code
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string result;
using (StreamReader rdr = new StreamReader(response.GetResponseStream()))
{
result = rdr.ReadToEnd();
}
return result;
当我运行这个时,我总是得到500个内部服务器错误。
我做错了什么?
我最近想出了一个更简单的方法来发布JSON,额外的步骤是从我的应用程序中的模型转换。注意,你必须为你的控制器创建模型[JsonObject]来获取值并进行转换。
要求:
var model = new MyModel();
using (var client = new HttpClient())
{
var uri = new Uri("XXXXXXXXX");
var json = new JavaScriptSerializer().Serialize(model);
var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PutAsync(uri,stringContent).Result;
// ...
}
模型:
[JsonObject]
[Serializable]
public class MyModel
{
public Decimal Value { get; set; }
public string Project { get; set; }
public string FilePath { get; set; }
public string FileName { get; set; }
}
服务器端:
[HttpPut]
public async Task<HttpResponseMessage> PutApi([FromBody]MyModel model)
{
// ...
}
HttpClient类型是一个比WebClient和HttpWebRequest更新的实现。WebClient和WebRequest都已被标记为过时。[1]
您可以简单地使用以下几行代码。
string myJson = "{'Username': 'myusername','Password':'pass'}";
using (var client = new HttpClient())
{
var response = await client.PostAsync(
"http://yourUrl",
new StringContent(myJson, Encoding.UTF8, "application/json"));
}
当你不止一次需要你的HttpClient时,建议只创建一个实例并重用它或使用新的HttpClientFactory。[2]
对于FTP,由于HttpClient不支持,我们建议使用第三方库。
@learn.microsoft.com [3]
从dotnet核心3.1开始,你可以使用System.Text.Json中的JsonSerializer来创建你的json字符串。
string myJson = JsonSerializer.Serialize(credentialsObj);