下面代码实现在Revit开发中向服务器发送一个post请求。
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace MyRevitPlugin
{
[Transaction(TransactionMode.Manual)]
public class Class2 : IExternalCommand
{
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
_ = SendToServer("hello, revit");
return Result.Succeeded;
}
private async Task<bool>SendToServer(string message)
{
// 构造body数据
RData rdata = new RData
{
Message = message
};
try
{
// 序列化
var content = new StringContent(JsonConvert.SerializeObject(rdata), Encoding.UTF8, "application/json");
// 发送请求
using (HttpClient client = new HttpClient())
{
var response = await client.PostAsync("http://localhost:3100/api/message", content);
if (response.IsSuccessStatusCode)
{
MessageBox.Show("数据已提交");
}
return response.IsSuccessStatusCode;
}
}
catch (SystemException ex)
{
MessageBox.Show($"Error submitting to server: {ex.Message}");
}
return false;
}
}
class RData
{
[JsonProperty("message")]
public string Message { get; set; }
}
}