如何解决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);
}
}
[结束 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,IDictionary
2 个参数) +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.WrappedAsyncResult
2.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.WrappedAsyncResult
1.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.WrappedAsyncResult
1.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.WrappedAsyncVoid
1.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.WrappedAsyncVoid
1.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.WrappedAsyncVoid
1.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,但是当我尝试重新打开保存的文件时,出现以下编码错误!!
希望这可以为其他人省去一些麻烦。请参阅@User9938 对 OP 的评论,他对我有很大帮助并为我节省了很多时间。谢谢!坦率地说,现在我的标题是正确的,我的其他一些尝试也可能有效。我把它们留了下来,以免其他人不得不逐个查找。:
people.sort(Comparator.comparingInt(Person::getAge));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。