C#.Net 4.8 框架如何将 API POST 调用中的查询字符串参数从标题更改为正文并在新选项卡中打开 PDF

如何解决C#.Net 4.8 框架如何将 API POST 调用中的查询字符串参数从标题更改为正文并在新选项卡中打开 PDF

[OP 评论/编辑]

我以为我已经完成了,但是在让这段代码工作后我保存了 PDF(非常感谢@User9938)。我可以保存PDF,但是当我打开文件时它没有打开,而是给出了“编码不正确的错误”......这是创建文件的代码(但不允许我保存它)!!有什么想法吗?

using (WebClient wc = new WebClient())
{
    //wc.Headers.Clear(); // Did not help
    wc.Headers.Add("Content-Type","application/xml");
    wc.Encoding = System.Text.Encoding.UTF8;
            
    //var data = wc.UploadString(URI,QS1);
    //Worked with ASCII & UTF8,but UTF8 is far superior and will save you pain if you have any international symbols (non USA letters)
    Byte[] buffer =  wc.UploadData(URI,"POST",System.Text.Encoding.UTF8.GetBytes(QS1)); 
    //Byte [] buffer = wc.UploadValues(api.BaseURI,myCol);
    if (buffer != null)
    {
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-length",buffer.Length.ToString());
        Response.BinaryWrite(buffer);
    }
}

尝试重新打开 PDF 时出现编码错误(保存后)。

enter image description here

[结束 OP 评论/编辑]

我的 C#(.NET Framework 4.8 代码)API 调用从 URI 返回 PDF。

公司更新了他们的 API,现在我必须在正文中传递参数(而不是查询字符串)。这是当前的“POST”版本,可在新的浏览器选项卡中打开 PDF。如何在正文中传递参数(而不是查询字符串)?这个完美的解决方案需要大量的挖掘才能使其工作,并且不适用于新系统。

    using (WebClient wc = new WebClient())
    {
        WebClient client = new WebClient();
        Byte[] buffer = client.DownloadData(https://destinationAPI.com/Request?A=Works&B=In&C=OldVersion);
        if (buffer != null)
        {
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-length",buffer.Length.ToString());
            Response.BinaryWrite(buffer);
        }
    }

我的尝试:(我在失败的行旁边放了注释。)感谢@user9938 的评论,我尝试了这个 this 的各种版本,但仍然出现 415 错误。

string QS1 = "A=this&B=is&c=EasyOnceYouGetTheRightAnswer";
Uri URI = "https://Mypost.com/RequestMyPDF";
string strURI = "https://Mypost.com/RequestMyPDF";

using (WebClient wc = new WebClient())
            {
                //These 3 attempts get a 415 Error
                //Byte[] buffer =  wc.UploadData(URI,System.Text.Encoding.ASCII.GetBytes(QS1)); //415 Error
                //Byte[] buffer = wc.UploadData(URI,System.Text.Encoding.UTF8.GetBytes(QS1));//415 Error
                Byte[] buffer = wc.UploadData(strURI,System.Text.Encoding.UTF8.GetBytes(QS1));//415 Error
                if (buffer != null)
                {
                    Response.ContentType = "application/pdf";
                    Response.AddHeader("content-length",buffer.Length.ToString());
                    Response.BinaryWrite(buffer);
                }
            }

另一个尝试(原始尝试)我有这段代码将数据拉入流阅读器,但“文本/纯文本”的“上下文类型”有效(“应用程序/pdf”返回415错误)。如果我可以将streamreader变成byte[],我想我可以使用上面的代码在新窗口中输出我的PDF。

try
{
    System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
    //req.ContentType = "application/pdf" //This generates a 415 Error
    req.ContentType = "text/plain"; //This returns data,but I don't think it will work with a PDF.
    req.Method = "POST";
    //We need to count how many bytes we're sending. Post'ed Faked Forms should be name=value&
    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
    req.ContentLength = bytes.Length;
    System.IO.Stream os = req.GetRequestStream();
    os.Write(bytes,bytes.Length); //Push it out there
    os.Close();
    System.Net.WebResponse resp = req.GetResponse();
    if (resp == null) return null;
            
    System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
    //READ to PDF and post in new window

    // Use ANSI encoding -also known as Encoding.GetEncoding(1252)??
    Encoding objEncoding = Encoding.Default;

    //StreamReader objSR = new StreamReader(sr.ReadToEnd().Trim(),objEncoding);
            
    //I want to open the pdf in a new tab,this is just an attempt to get ito to work... 
    //This creates an EMPTY PDF 
    StreamWriter objSW = new StreamWriter(@"c:\temp\Destination123.PDF",false,objEncoding);
    objSW.Write(sr.ReadToEnd().Trim());
    objSW.Close();
   
    //Byte[] buffer = ?? How to convert StreamWriter to BYTE!?!// (Old code was "Byte[] buffer = client.DownloadData(api.URI);")
    //if (buffer != null)
    //{
    //    Response.ContentType = "application/pdf";
    //    Response.AddHeader("content-length",buffer.Length.ToString());
    //    Response.BinaryWrite(buffer);
    //}
            
    return "Have we a PDF?!?!";
}
catch (Exception ex)
{
    return  ex.Message;
}

我对最后一个 415 错误的堆栈跟踪:

[WebException:远程服务器返回错误:(415) 不支持的媒体类型。] System.Net.WebClient.UploadDataInternal(Uri地址,String方法,Byte[]数据,WebRequest&请求)+317 System.Net.WebClient.UploadData(Uri地址,String方法,Byte[]数据)+160 System.Net.WebClient.UploadData(String address,String method,Byte[] data) +38 MyApp.Controllers.StatementsController.GetIndividualPDF(List1 model) +5328 lambda_method(Closure,ControllerBase,Object[] ) +103 System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller,Object[] parameters) +14 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext,IDictionary2 个参数) +157 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext,ActionDescriptor actionDescriptor,IDictionary2 parameters) +27 System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult,ActionInvocation innerInvokeState) +22 System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +29 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32 System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +50 System.Web.Mvc.Async.<>c__DisplayClass48.<InvokeActionMethodFilterAsynchronouslyRecursive>b__41() +228 System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34 System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26 System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100 System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27 System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult,ExecuteCoreState innerState) +13 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36 System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult,Controller controller) +12 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +22 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10 System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult,ProcessRequestState innerState) +21 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29 System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult 结果) +9 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9836613 System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +50 System.Web.HttpApplication.ExecuteStep(IExecutionStep step,Boolean&completedSynchronously) +163

解决方法

!!!下面的代码创建了 PDF,它看起来很完美。我可以保存 PDF,但是当我尝试重新打开保存的文件时,出现以下编码错误!!enter image description here

希望这可以为其他人省去一些麻烦。请参阅@User9938 对 OP 的评论,他对我有很大帮助并为我节省了很多时间。谢谢!坦率地说,现在我的标题是正确的,我的其他一些尝试也可能有效。我把它们留了下来,以免其他人不得不逐个查找。:

 people.sort(Comparator.comparingInt(Person::getAge));

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-