- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
公共(public)字符串 HttpCall(string NvpRequest)
方法中出现以下异常:
'System.Net.ProtocolViolationException' {"You must write ContentLength bytes to the request stream before calling [Begin]GetResponse."}
出现在这行代码
//Retrieve the Response returned from the NVP API call to PayPal.
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
代码如下:
using System;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;
using System.Data;
using System.Configuration;
using System.Web;
using WingtipToys;
using WingtipToys.Models;
using System.Collections.Generic;
using System.Linq;
public class NVPAPICaller
{
//Flag that determines the PayPal environment (live or sandbox)
private const bool bSandbox = true;
private const string CVV2 = "CVV2";
// Live strings.
private string pEndPointURL = "https://api-3t.paypal.com/nvp";
private string host = "www.paypal.com";
// Sandbox strings.
private string pEndPointURL_SB = "https://api-3t.sandbox.paypal.com/nvp";
private string host_SB = "www.sandbox.paypal.com";
private const string SIGNATURE = "SIGNATURE";
private const string PWD = "PWD";
private const string ACCT = "ACCT";
//Replace <Your API Username> with your API Username
//Replace <Your API Password> with your API Password
//Replace <Your Signature> with your Signature
//
// 4/28/2016 Updated by Mike to test the Paypal API
// Commented out these three (3) lines below and add new credentials
//
//public string APIUsername = "<Your API Username>";
//private string APIPassword = "<Your API Password>";
//private string APISignature = "<Your Signature>";
public string APIUsername = "test@test.com";
private string APIPassword = "Testing123!";
private string APISignature = "MySignature";
private string Subject = "";
private string BNCode = "PP-ECWizard";
//HttpWebRequest Timeout specified in milliseconds
private const int Timeout = 15000;
private static readonly string[] SECURED_NVPS = new string[] { ACCT, CVV2, SIGNATURE, PWD };
public void SetCredentials(string Userid, string Pwd, string Signature)
{
APIUsername = Userid;
APIPassword = Pwd;
APISignature = Signature;
}
public bool ShortcutExpressCheckout(string amt, ref string token, ref string retMsg)
{
if (bSandbox)
{
pEndPointURL = pEndPointURL_SB;
host = host_SB;
}
string returnURL = "https://localhost:44300/Checkout/CheckoutReview.aspx";
string cancelURL = "https://localhost:44300/Checkout/CheckoutCancel.aspx";
NVPCodec encoder = new NVPCodec();
encoder["METHOD"] = "SetExpressCheckout";
encoder["RETURNURL"] = returnURL;
encoder["CANCELURL"] = cancelURL;
encoder["BRANDNAME"] = "MyBrandNameDuringTesting";
encoder["PAYMENTREQUEST_0_AMT"] = amt;
encoder["PAYMENTREQUEST_0_ITEMAMT"] = amt;
encoder["PAYMENTREQUEST_0_PAYMENTACTION"] = "Sale";
encoder["PAYMENTREQUEST_0_CURRENCYCODE"] = "USD";
// Get the Shopping Cart Products
using (WingtipToys.Logic.ShoppingCartActions myCartOrders = new WingtipToys.Logic.ShoppingCartActions())
{
List<CartItem> myOrderList = myCartOrders.GetCartItems();
for (int i = 0; i < myOrderList.Count; i++)
{
encoder["L_PAYMENTREQUEST_0_NAME" + i] = myOrderList[i].Product.ProductName.ToString();
encoder["L_PAYMENTREQUEST_0_AMT" + i] = myOrderList[i].Product.UnitPrice.ToString();
encoder["L_PAYMENTREQUEST_0_QTY" + i] = myOrderList[i].Quantity.ToString();
}
}
string pStrrequestforNvp = encoder.Encode();
string pStresponsenvp = HttpCall(pStrrequestforNvp);
NVPCodec decoder = new NVPCodec();
decoder.Decode(pStresponsenvp);
string strAck = decoder["ACK"].ToLower();
if (strAck != null && (strAck == "success" || strAck == "successwithwarning"))
{
token = decoder["TOKEN"];
string ECURL = "https://" + host + "/cgi-bin/webscr?cmd=_express-checkout" + "&token=" + token;
retMsg = ECURL;
return true;
}
else
{
retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" +
"Desc=" + decoder["L_SHORTMESSAGE0"] + "&" +
"Desc2=" + decoder["L_LONGMESSAGE0"];
return false;
}
}
public bool GetCheckoutDetails(string token, ref string PayerID, ref NVPCodec decoder, ref string retMsg)
{
if (bSandbox)
{
pEndPointURL = pEndPointURL_SB;
}
NVPCodec encoder = new NVPCodec();
encoder["METHOD"] = "GetExpressCheckoutDetails";
encoder["TOKEN"] = token;
string pStrrequestforNvp = encoder.Encode();
string pStresponsenvp = HttpCall(pStrrequestforNvp);
decoder = new NVPCodec();
decoder.Decode(pStresponsenvp);
string strAck = decoder["ACK"].ToLower();
if (strAck != null && (strAck == "success" || strAck == "successwithwarning"))
{
PayerID = decoder["PAYERID"];
return true;
}
else
{
retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" +
"Desc=" + decoder["L_SHORTMESSAGE0"] + "&" +
"Desc2=" + decoder["L_LONGMESSAGE0"];
return false;
}
}
public bool DoCheckoutPayment(string finalPaymentAmount, string token, string PayerID, ref NVPCodec decoder, ref string retMsg)
{
if (bSandbox)
{
pEndPointURL = pEndPointURL_SB;
}
NVPCodec encoder = new NVPCodec();
encoder["METHOD"] = "DoExpressCheckoutPayment";
encoder["TOKEN"] = token;
encoder["PAYERID"] = PayerID;
encoder["PAYMENTREQUEST_0_AMT"] = finalPaymentAmount;
encoder["PAYMENTREQUEST_0_CURRENCYCODE"] = "USD";
encoder["PAYMENTREQUEST_0_PAYMENTACTION"] = "Sale";
string pStrrequestforNvp = encoder.Encode();
string pStresponsenvp = HttpCall(pStrrequestforNvp);
decoder = new NVPCodec();
decoder.Decode(pStresponsenvp);
string strAck = decoder["ACK"].ToLower();
if (strAck != null && (strAck == "success" || strAck == "successwithwarning"))
{
return true;
}
else
{
retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" +
"Desc=" + decoder["L_SHORTMESSAGE0"] + "&" +
"Desc2=" + decoder["L_LONGMESSAGE0"];
return false;
}
}
public string HttpCall(string NvpRequest)
{
string url = pEndPointURL;
string strPost = NvpRequest + "&" + buildCredentialsNVPString();
strPost = strPost + "&BUTTONSOURCE=" + HttpUtility.UrlEncode(BNCode);
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = Timeout;
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
try
{
using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
{
myWriter.Write(strPost);
}
}
catch (Exception e)
{
// Log the exception.
WingtipToys.Logic.ExceptionUtility.LogException(e, "HttpCall in PayPalFunction.cs");
}
//Retrieve the Response returned from the NVP API call to PayPal.
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
string result;
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}
return result;
}
private string buildCredentialsNVPString()
{
NVPCodec codec = new NVPCodec();
if (!IsEmpty(APIUsername))
codec["USER"] = APIUsername;
if (!IsEmpty(APIPassword))
codec[PWD] = APIPassword;
if (!IsEmpty(APISignature))
codec[SIGNATURE] = APISignature;
if (!IsEmpty(Subject))
codec["SUBJECT"] = Subject;
codec["VERSION"] = "88.0";
return codec.Encode();
}
public static bool IsEmpty(string s)
{
return s == null || s.Trim() == string.Empty;
}
}
public sealed class NVPCodec : NameValueCollection
{
private const string AMPERSAND = "&";
private const string EQUALS = "=";
private static readonly char[] AMPERSAND_CHAR_ARRAY = AMPERSAND.ToCharArray();
private static readonly char[] EQUALS_CHAR_ARRAY = EQUALS.ToCharArray();
public string Encode()
{
StringBuilder sb = new StringBuilder();
bool firstPair = true;
foreach (string kv in AllKeys)
{
string name = HttpUtility.UrlEncode(kv);
string value = HttpUtility.UrlEncode(this[kv]);
if (!firstPair)
{
sb.Append(AMPERSAND);
}
sb.Append(name).Append(EQUALS).Append(value);
firstPair = false;
}
return sb.ToString();
}
public void Decode(string nvpstring)
{
Clear();
foreach (string nvp in nvpstring.Split(AMPERSAND_CHAR_ARRAY))
{
string[] tokens = nvp.Split(EQUALS_CHAR_ARRAY);
if (tokens.Length >= 2)
{
string name = HttpUtility.UrlDecode(tokens[0]);
string value = HttpUtility.UrlDecode(tokens[1]);
Add(name, value);
}
}
}
public void Add(string name, string value, int index)
{
this.Add(GetArrayName(index, name), value);
}
public void Remove(string arrayName, int index)
{
this.Remove(GetArrayName(index, arrayName));
}
public string this[string name, int index]
{
get
{
return this[GetArrayName(index, name)];
}
set
{
this[GetArrayName(index, name)] = value;
}
}
private static string GetArrayName(int index, string name)
{
if (index < 0)
{
throw new ArgumentOutOfRangeException("index", "index cannot be negative : " + index);
}
return name + index;
}
最佳答案
strPost.Length(字符串中字符的数量)可以完全不同于用于存储字符串的字节数,因为编码。
为确保正确的大小,首先获取字符串的二进制数组并将其用作大小并将其写入流:
public string HttpCall(string NvpRequest)
{
string url = pEndPointURL;
string strPost = NvpRequest + "&" + buildCredentialsNVPString();
strPost = strPost + "&BUTTONSOURCE=" + HttpUtility.UrlEncode(BNCode);
var byteStr = Encoding.UTF8.GetBytes(strPost);
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = Timeout;
objRequest.Method = "POST";
objRequest.ContentLength = byteStr.Length;
try
{
using(var str = objRequest.GetRequestStream())
str.Write(byteStr, 0, byteStr.Length);
}
catch (Exception e)
{
// Log the exception.
WingtipToys.Logic.ExceptionUtility.LogException(e, "HttpCall in PayPalFunction.cs");
}
//Retrieve the Response returned from the NVP API call to PayPal.
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
string result;
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}
return result;
}
关于c# - 'System.Net.ProtocolViolationException' {"You must write ContentLength bytes to the request stream before calling [Begin]GetResponse."},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36918570/
我正在尝试实现具有以下签名的方法: public static Pair, Stream> flatten(Iterator, Stream>> iterator); 该方法的目标是将每种流类型展平
我有两个流从两个不同的 api 获取。 Stream get monthOutStream => monthOutController.stream; Stream get resultOutStre
Stream.of(int[])返回 Stream ,而 Stream.of(String[])返回 Stream . 为什么这两种方法的行为不同?两者都应该返回 Stream和 Stream或 St
我正在使用 rxdart在 dart 中处理流的包。我被困在处理一个特殊的问题上。 请看一下这个虚拟代码: final userId = BehaviorSubject(); Stream getSt
我到处都找遍了,还是没弄明白。我知道你可以用流建立两个关联: 用于支持数据存储的包装器意味着作为消费者和供应商之间的抽象层 数据随着时间的推移变得可用,而不是一次全部 SIMD 代表单指令,多数据;在
考虑下面的代码: List l=new ArrayList<>(); l.add(23);l.add(45);l.add(90); Stream str=l.stream
我有一个大型主干/requirejs 应用程序,我想迁移到 webpack,最新的“webpack”:“^4.27.1”,但我遇到了一个我无法解决的错误。 我一直在阅读 https://webpack
我正在使用 xmpp 开发聊天应用程序,根据我们的要求,我们有三台服务器 Apache Tomcat 7、ejabbered 2.1.11 和 mysql 5.5, to run xmppbot on
我知道如何使用 Java 库,并且我可以编写一些循环来执行我需要的操作,但问题更多,为什么 scala.collection.JavaConverters 中没有任何内容或scala.collecti
我正在尝试创建一个单一的衬里,它应该计算一个非常长的文本文件中的唯一单词。独特的词例如:márya fëdorovna scarlet-liveried,...所以基本上都是非英语词。 我的问题是我的
如果我有以下情况: StreamWriter MySW = null; try { Stream MyStream = new FileStream("asdf.txt"); MySW =
有人可以帮我将以下语句转换为 Java8: 我有一个像这样的 HashMap : private Map, List>> someMap; 我想在java8中转换以下逻辑: private Strin
有人可以帮我将以下语句转换为 Java8: 我有一个像这样的 HashMap : private Map, List>> someMap; 我想在java8中转换以下逻辑: private Strin
考虑两种测试方法parallel()和sequential(): @Test public void parallel() throws Exception { System.ou
我是 NodeJS 的新手,我基本上想做的是通过 HTTP 将 .pdf 上传到我的服务器。我正在使用 POST rquest 来处理 Content-Type multipart/form-data
哪个更好:MemoryStream.WriteTo(Stream destinationStream) 或 Stream.CopyTo(Stream destinationStream)?? 我正在谈
给定一个 Stream,我想创建一个新的 Stream,其中的元素在它们之间有时间延迟。 我尝试使用 tokio_core::reactor::Timeout 和 Stream 的 and_then
我是 Kafka Streams 和 Spring Cloud Stream 的新手,但在将集成相关代码移动到属性文件方面已经阅读了有关它的好东西,因此开发人员可以主要专注于事物的业务逻辑方面。 这里
源代码看起来非常相似:pump , pipe .为什么我要使用一个而不是另一个?一个只是另一个的更好版本吗? 最佳答案 Stream.pipe 现在显然是自 0.3.x 以来的首选方法,因此尽可能尝试
我正在寻找是否有更好的方法来解决我不得不使用这些签名的困境(注意:由于 Spock 测试,T[][] 是必需的,我提供 T[][] 作为数据提供商) 我的方法签名是: public T[][] cr
我是一名优秀的程序员,十分优秀!