My Perl脚本将推送通知发送到Apple APNS服务器。它起作用,除非我尝试发送表情符号(特殊字符)。
use DBI;
use JSON;
use Net::APNS::Persistent;
use Data::Dumper;
use Encode;
my $cfg;
my $apns;
...;
sub connect {
my ($sandbox, $cert, $key, $pass) = $cfg->getAPNSServer();
$apns = Net::APNS::Persistent->new({
sandbox => $sandbox,
cert => $cert,
key => $key,
}) or die("[-] Unable to connect to APNS server");
}
sub push {
my $msg = $_[1];
Logger::log(5, "[APNS Client] Got message ".Dumper($msg));
#Encode::_utf8_off($msg);
utf8::encode($msg);
my $pack = decode_json($msg);
my ($token, $payload) = @{$pack};
Logger::log(5, "Sending push with token: $token and Data: \n".Dumper($payload));
$apns->queue_notification(
$token,
$payload
);
$apns->send_queue;
}
因此在push子例程中,我使用下面给出的格式传递JSON数据。我的问题在于表情符号\x{2460}
。你可以看到我添加了这一行
utf8::encode($msg);
在解码数据之前。如果我删除此行,则在解码JSON数据时会出现错误
Wide character in subroutine entry at .....
添加上面的行后,我可以解码我的JSON数据。但是当我尝试在下一行($apns->send_queue
)中写入套接字时给出
Cannot decode string with wide characters at /usr/lib/perl/5.10/Encode.pm line 176
我该如何解决这个问题?
["token",
{
"aps":{
"alert":"Alert: \x{2460}",
"content-available":1,
"badge":2,
"sound":"default.aiff"
},
"d":"Meta"
}
]
转储输出
[-] [ 2015-08-25T20:03:15 ] [APNS Client] Got message $VAR1 = "[\"19c360f37681035730a26cckjgkjgkj58b2d20326986f4265ee802c103f51\",{\"aps\":{\"alert\":\"Alert: \x{24bc}\",\"content-available\":1,\"badge\":2,\"sound\":\"default.aiff\"},\"d\":\"Meta\"}]";
[-] [ 2015-08-25T20:03:15 ] Sending push with token: 119c360f37681035730a26cckjgkjgkj58b2d20326986f4265ee802c103f51 and Data:
$VAR1 = {
'aps' => {
'alert' => "Alert: \x{24bc}",
'content-available' => 1,
'badge' => 2,
'sound' => 'default.aiff'
},
'd' => 'Meta'
};
[x] [ 2015-08-25T20:03:15 ] [APNS Client] Error writing to socket. Reconnecting : Cannot decode string with wide characters at /usr/lib/perl/5.10/Encode.pm line 176.
答案 0 :(得分:3)
在发送之前,您可能需要在$payload
中对警报进行UTF-8编码。您也可以使用from_json
代替decode_json
来避免第一个编码步骤:
sub push {
my $msg = $_[1];
Logger::log(5, "[APNS Client] Got message ".Dumper($msg));
my $pack = from_json($msg);
my ($token, $payload) = @{$pack};
Logger::log(5, "Sending push with token: $token and Data: \n".Dumper($payload));
# UTF-8 encode before sending.
utf8::encode($payload->{aps}{alert});
$apns->queue_notification(
$token,
$payload
);
$apns->send_queue;
}
答案 1 :(得分:3)
首先,decode_json
期望使用UTF-8编码JSON,因此如果您从“已解码”JSON开始,则按照您的方式对其进行编码是合适的。
utf8::encode( my $json_utf8 = $json_uni );
my $data = decode_json($json_utf8);
但是,使用from_json
会更简单。
my $data = from_json($json_uni);
现在回答你的问题。编写Net :: APNS :: Persistent的人搞砸了很多时间。我查看了源代码,他们希望使用UTF-8编码警报消息。添加以下内容将使您的结构符合模块的不可取的期望:
utf8::encode(
ref($payload->{aps}{alert}) eq 'HASH'
? $payload->{aps}{alert}{body}
: $payload->{aps}{alert}
);
如果遇到其他问题,我不会感到惊讶。值得注意的是,这些模块使用了 bytes 模块,这是一个确定的错误信号。