【问题标题】:Converting Java code to C# httpClient POST custom request to a conversion server将 Java 代码转换为 C# httpClient POST 自定义请求到转换服务器
【发布时间】:2021-04-07 06:13:57
【问题描述】:

我有一个使用 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 中的工作方式并从生成的代码 sn-p 开始。挑战在于识别源文档以便上传(对于每个文件参数的用途似乎有点混乱):

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);
            }
        }
    }
}

【问题讨论】:

  • 这能回答你的问题吗? Upload image using HttpClient
  • 感谢 Eldar - 我遇到了这个问题,但无法取得任何进展 - 我正在添加一些 C# 代码,让我在其中的一部分 - Http 请求至少得到了响应。跨度>

标签: java c# post httpclient documents4j


【解决方案1】:

替代解决方案 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,标题:{
接受:application/pdf Converter-Job-Priority: 1000 Content-Type: application/vnd.com.documents4j.any-msword }response:StatusCode: 200, 原因短语:'OK',版本:1.1,内容: System.Net.Http.StreamContent,标头:{ 变化:Accept-Encoding
传输编码:分块日期:2021 年 4 月 12 日星期一 06:49:45 GMT
内容类型:application/pdf

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 2018-05-31
    相关资源
    最近更新 更多