我在 Windows 商店应用程序项目中尝试使用Convertapi,我想发送一个 .docx 文件并获得一个 pdf 文件作为回报,我正在尝试发布一个帖子,但我不确定它是如何完成的,这就是我目前所拥有的,但它不起作用。
private async Task GeneratePdfContract(string path) {
try {
var data = new List < KeyValuePair < string, string >> {
new KeyValuePair < string, string > ("Api", "5"),
new KeyValuePair < string, string > ("ApiKey", "419595049"),
new KeyValuePair < string, string > ("File", "" + stream2),
};
await PostKeyValueData(data);
} catch (Exception e) {
Debug.WriteLine(e.Message);
}
}
private async Task PostKeyValueData(List < KeyValuePair < string, string >> values) {
var httpClient = new HttpClient();
var response = await httpClient.PostAsync("http://do.convertapi.com/Word2Pdf", new FormUrlEncodedContent(values));
var responseString = await response.Content.ReadAsStringAsync();
}
我应该如何发送我的帖子以发送 .docx 文件并获得 .pdf 文件作为回报?
编辑:
private async Task GeneratePdfContract(string path)
{
try
{
using (var client = new System.Net.Http.HttpClient())
{
using (var multipartFormDataContent = new MultipartFormDataContent())
{
var values = new[]
{
new KeyValuePair<string, string>("ApiKey", "413595149")
};
foreach (var keyValuePair in values)
{
multipartFormDataContent.Add(new StringContent(keyValuePair.Value), String.Format("\"{0}\"", keyValuePair.Key));
}
StorageFolder currentFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync(Constants.DataDirectory);
StorageFile outputFile = await currentFolder.GetFileAsync("file.docx");
byte[] fileBytes = await outputFile.ToBytes();
//multipartFormDataContent.Add(new ByteArrayContent(FileIO.ReadBufferAsync(@"C:\test.docx")), '"' + "File" + '"', '"' + "test.docx" + '"');
multipartFormDataContent.Add(new ByteArrayContent(fileBytes));
const string requestUri = "http://do.convertapi.com/word2pdf";
var response = await client.PostAsync(requestUri, multipartFormDataContent);
if (response.IsSuccessStatusCode)
{
var responseHeaders = response.Headers;
var paths = responseHeaders.GetValues("OutputFileName").First();
var path2 = Path.Combine(@"C:\", paths);
StorageFile sampleFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(@"C:\Users\Thought\AppData\Local\Packages\xxxxx_apk0zz032bzya\LocalState\Data\");
await FileIO.WriteBytesAsync(sampleFile, await response.Content.ReadAsByteArrayAsync());
}
else
{
Debug.WriteLine("Status Code : {0}", response.StatusCode);
Debug.WriteLine("Status Description : {0}", response.ReasonPhrase);
}
}
}
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
}
@Tomas 尝试稍微调整您的答案,因为 Windows 商店应用程序上似乎没有“File.ReadAllBytes”,我得到了这个回复:\