我想使用Spring MVC的MessageConverter实例化一个名为IPNMessage的对象。 SDK link
Paypal IPN消息采用text-plain
格式,我想将其反序列化为IPNMessage对象。
cmd = _notify-validate&payment_type = instant&payment_date = Fri Apr 08 2016 = US&address_zip = 95131&ADDRESS_STATE = CA&ADDRESS_CITY =圣何塞&address_street = 123的任何街道和商业=卖家@ paypalsandbox.com&RECEIVER_EMAIL =卖家@ paypalsandbox.com&receiver_id =卖家@ paypalsandbox.com&residence_country = US&item_name1 =东西&item_number1 = AK-1234税额= 2.02&mc_currency = USD&mc_fee = 0.44 mc_gross = 12.34&mc_gross_1 = 12.34&mc_handling = 2.06&mc_handling1 = 1.67&mc_shipping = 3.02&mc_shipping1 = 1.02&txn_type = cart&txn_id = 297973429&notify_version = 2.1&custom = xyz123&invoice = abc1234&test_ipn = 1&verify_sign = AFcWxV4B1E7B1E4B1E4B1E7B4E7B0E4B0E4B0E4B0E0E4B0E0E7B0E0E0E0E0B0E0B0C0E0B0茨册_国传
消息转换类:
public class PaypalIPNHttpMessageConverter extends AbstractHttpMessageConverter<IPNMessage> {
public PaypalIPNHttpMessageConverter() {
super(new MediaType("application", "text-plain"), MediaType.ALL);
}
@Override
protected boolean supports(Class<?> clazz) {
return false;
}
@Override
protected IPNMessage readInternal(Class<? extends IPNMessage> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
//Converts HTTPRequest into map<string,string> that IPNMessage can then parse
String requestString = IOUtils.toString(inputMessage.getBody(), "UTF-8");
Map<String, String[]> requestMap = new LinkedHashMap<>();
for (String keyValue : requestString.split("&")) { //each key value is delimited by &
String[] pairs = keyValue.split("=", 2); // = pairs a key to a value
requestMap.put(pairs[0], pairs[1].split(",")); // , splits multiple values for that key
}
return new IPNMessage(requestMap);
}
@Override
protected void writeInternal(IPNMessage ipnMessage, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
}
}
在servlet.xml中配置
<bean class="com.kappa.PaymentController">
<property name="delegate" ref="paymentService"/>
<property name="paypalDelegate" ref="paypalIPNService"/>
<property name="messageConverter" ref="paypalIPNHttpMessageConverter"/>
</bean>
控制器端点
@Override
@Auditable
@RequestMapping(value = "/processPaypalIPNRequest.do", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void processPaypalIPNRequest(@RequestBody IPNMessage ipnMessage) {
paypalDelegate.processPaypalIPNRequest(ipnMessage);
}
当我触发POST请求时,我收到HTTP 415,说我的请求正文不受支持。
我是否缺少Spring的进一步配置?
注意:我在消息转换器类中放置了断点,但未达到断点,因此此问题在更高级别上出现,但不确定在哪里。
最佳答案
IPNMessage
具有一个预期有请求的构造函数。因此,最简单的解决方案是像这样更改您的方法:
public void processPaypalIPNRequest(HttpServletRequest request) {
paypalDelegate.processPaypalIPNRequest(new IPNMessage(request));
}
如果您想要自己的消息转换器,则理想情况下也可以执行
new IPNMessage(request)
。