1

我有一个使用 Java 的示例工作解决方案,但我需要一个可以从遗留数据库系统调用的 C# 解决方案。

所以基本上创建一个带有自定义标题的请求,加载一个 Word 文档,然后发送请求。然后,服务器将转换 Word 文档并返回 PDF,然后需要将其保存到磁盘。

有人可以帮忙吗。

Java 代码

    import java.io.*;
    import java.net.HttpURLConnection;
    import java.net.URL;
    public class NewMain {
    public static void main(String[] args) throws IOException {
    String source =  args[0];
    String target =  args[1];
    
    URL url = new URL("http://localhost:9998");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", 
    "application/vnd.com.documents4j.any-msword");
    conn.setRequestProperty("Accept", "application/pdf");
    conn.setRequestProperty("Converter-Job-Priority", "1000");
    //        File wordFile = new File("C:/temp2/Sample.doc");
    File wordFile = new File(source);
    InputStream targetStream = new FileInputStream(wordFile);
    OutputStream os = conn.getOutputStream();
    long length = targetStream.transferTo(os);
    os.flush();
    if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
       throw new RuntimeException("Failed : HTTP error code : "
       + conn.getResponseCode());
    }
    InputStream in = conn.getInputStream();
    //        OutputStream out = new FileOutputStream("C:/temp2/Sample-BBB-doc.pdf");
    OutputStream out = new FileOutputStream(target);
    byte[] buffer = new byte[1024];
    int len;
    while ((len = in.read(buffer)) != -1) {
       out.write(buffer, 0, len);
    }
    in.close();
    out.close();
    os.close();
    conn.disconnect();
    }
    }

以下是我一直在使用的 C# 代码 [注意尚未尝试保存返回的 PDF] - 下面是服务器响应:

using System;
using System.Net;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http.Headers;

namespace HttpPOST10
{
    class Program
    {
        public static string MyUri { get; private set; }
        static void Main(string[] args)
        {
            string url = "http://localhost:9998";
            Uri myUri = new Uri(url);
            string filePath = @"C:\temp2";
            string srcFilename = @"C:\temp2\Sample.doc";
            string destFileName = @"C:\temp3\Sample.pdf";
            UploadFile(url, filePath, srcFilename, destFileName);
        }
        private static bool UploadFile(string url, string filePath, string srcFilename, string destFileName)
        {
            HttpClient httpClient = new HttpClient();
            using var fileStream = new FileStream(srcFilename, FileMode.Open);
            var fileInfo = new FileInfo(srcFilename);
            var httpRequestMessage = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                RequestUri = new Uri(url),
                Headers = {
                        { HttpRequestHeader.ContentType.ToString(), "application/vnd.com.documents4j.any-msword" },
                        { HttpRequestHeader.Accept.ToString(), "application/pdf" },
                        {"Converter-Job-Priority", "1000"}
                        },
                Content = new StreamContent(fileStream)
            };
            Console.Write("httpRequestMessage:" + httpRequestMessage);
            var response = httpClient.SendAsync(httpRequestMessage).Result;
            Console.Write("response:" + response);
            return true;
        }
    }
}

Http 响应:

httpRequestMessage:Method: POST, RequestUri: 'http://localhost:9998/', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  ContentType: application/vnd.com.documents4j.any-msword
  Accept: application/pdf
  Converter-Job-Priority: 1000
}response:StatusCode: 500, ReasonPhrase: 'Request failed.', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Connection: close
  Content-Length: 1031
  Content-Type: text/html; charset=ISO-8859-1

替代解决方案 restSharp

我今天取得了一些进展,并设法在 restSharp 中创建了一个基本的工作解决方案。这源于调查 Postman 中的工作方式并从生成的代码片段开始。挑战在于识别源文档以便可以上传(对于每个文件参数的用途似乎有点混乱):

using System;
using System.IO;
using System.Net;
using RestSharp;
using RestSharp.Extensions;

namespace HttpPOST12RestSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            var source = "C:\\temp2\\Sample.doc";
            var target = @"C:\temp3\Sample-HttpPOST12RestSharp.pdf";

            var client = new RestClient("http://localhost:9998");
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/vnd.com.documents4j.any-msword");
            request.AddHeader("Accept", "application/pdf");
            request.AddHeader("Converter-Job-Priority", " 1000");
            request.AddParameter("application/vnd.com.documents4j.any-msword", File.ReadAllBytes(source), Path.GetFileName(source), ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);

            Console.WriteLine("response.StatusCode: " + response.StatusCode);

            if (response.StatusCode != HttpStatusCode.OK)
            { 
                throw new Exception($"Unable to download file");
            }
            else
            { 
            response.RawBytes.SaveAs(target);
            Console.WriteLine("Target Document: " + target);
            }
        }
    }
}
4

1 回答 1

0

替代解决方案 HttpClient / HttpRequestMessage

此解决方案使用没有外部库的 HttpClient / HttpRequestMessage 并将返回的 PDF 响应保存到磁盘。

using System;
using System.Net;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;

namespace HttpPOST10
{
    class Program
    {
        public static string MyUri { get; private set; }
        static void Main(string[] args)
        {
            string url = "http://localhost:9998";
//            string url = "http://localhost:8888"; // Fiddler
            Uri myUri = new Uri(url);
            string srcFilename = @"C:\temp2\Sample.doc";
            string destFileName = @"C:\temp3\Sample-HttpPOST10.pdf";

            UploadFileAsync(url, srcFilename, destFileName);
        }
        private static async System.Threading.Tasks.Task<bool> UploadFileAsync(string url, string srcFilename, string destFileName)
        {
            HttpClient httpClient = new HttpClient();
            byte[] data;
            data = File.ReadAllBytes(srcFilename);

            HttpContent content = new ByteArrayContent(data);
            content.Headers.Add("Content-Type", "application/vnd.com.documents4j.any-msword");

            var httpRequestMessage = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                RequestUri = new Uri(url),
                Headers = {
//                    { HttpRequestHeader.ContentType.ToString(), "application/vnd.com.documents4j.any-msword" },
                    { HttpRequestHeader.Accept.ToString(), "application/pdf" },
                    { "Converter-Job-Priority", "1000" },
                },
                Content = content
            };

            Console.Write("httpRequestMessage:" + httpRequestMessage);
            var response = httpClient.SendAsync(httpRequestMessage).Result;
            Console.Write("response:" + response);

            using (var fs = new FileStream(destFileName, FileMode.CreateNew))
            {
                await response.Content.CopyToAsync(fs);
            }

            return true;
        }
    }
}

请求/响应

httpRequestMessage:方法:POST,RequestUri:'http://localhost:9998/',版本:1.1,内容:System.Net.Http.ByteArrayContent,标题:{
接受:应用程序/pdf Converter-Job-Priority:1000 Content-类型:application/vnd.com.documents4j.any-msword }response:StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Vary: Accept-Encoding
Transfer-编码:分块日期:星期一,2021 年 4 月 12 日 06:49:45 GMT
内容类型:application/pdf

于 2021-04-12T06:57:09.620 回答