我有一個 WindowsForm ADO.NET 應用程式,它將使用對 Flask api 的 post 方法呼叫并上傳一個 xml 檔案
這是我使用 python 呼叫 api 的方式:
import requests
API_URL = 'http://localhost:5000'
with open('result.xml') as fp:
content = fp.read()
response = requests.post(
'{}/files/result.xml'.format(API_URL), data=content
)
我一直在研究如何使用方法 post 呼叫 api 并以 c# windows 形式上傳檔案
這是我最終的結果:
上傳功能:
private async Task<IRestResponse> UploadAsync(string fileName, string server)
{
var client = new RestClient(server);
var request = new RestRequest("/files", Method.POST);
XmlDocument doc = new XmlDocument();
// init XMLDocument and load customer in it
doc = new XmlDocument();
doc.Load(@"" fileName "");
// Update (PUT) customer
request = new RestRequest("/files", Method.POST);
request.Parameters.Clear();
request.AddParameter("text/xml;charset=utf-8", doc.InnerXml, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
return response;
}
函式呼叫:
private async void button2_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(label1.Text))
{
string url = "http://localhost:5000";
IRestResponse restResponse = await UploadAsync(label1.Text,url);
if (restResponse.StatusCode == System.Net.HttpStatusCode.OK)
MessageBox.Show("You have successfully uploaded the file", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
單擊按鈕不執行任何操作沒有錯誤并且不發送檔案
關于如何解決這個問題的任何想法?
uj5u.com熱心網友回復:
為了解決這個問題,我使用了這段代碼:
XmlDocument doc = new XmlDocument();
doc = new XmlDocument();
doc.Load(@"" textBox1.Text "");
var client = new RestClient("http://appapi9.azurewebsites.net/files/filethatillcheck.xml");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/xml");
request.AddParameter("application/xml","" doc.OuterXml "", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
MessageBox.Show("done");
我必須加載 x??ml 檔案并發送它的內容
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/406571.html
標籤:
上一篇:如何使用c#中的foreach回圈更改Winforms中多個DateTimePicker欄位的CustomFormat?
