简体   繁体   English

如何以Twitter API期望的格式在Dart中进行网址编码?

[英]How do I url-encode in Dart in the format that the Twitter API expects?

I wrote some code to post tweets in C#. 写了一些代码在C#中发布推文。 One of the things that tripped me up was the url-encoding of data since there seemed to be many options: 使我震惊的一件事是数据的url编码,因为似乎有很多选择:

var input = "Hello Ladies + Gentlemen, a signed OAuth request!";
var expected = "Hello%20Ladies%20%2B%20Gentlemen%2C%20a%20signed%20OAuth%20request%21";

Console.WriteLine(WebUtility.UrlEncode(input) == expected); // False
Console.WriteLine(Uri.EscapeUriString(input) == expected); // False
Console.WriteLine(Uri.EscapeDataString(input) == expected); // True

I'm now trying to do the same thing in Dart. 我现在正在尝试在Dart中执行相同的操作。 I've tried all the encode methods in the Uri class, but none seem to output the same. 我已经尝试了Uri类中的所有编码方法,但似乎都没有输出相同的方法。

Code: ( DartPad ) 代码:( DartPad

print(Uri.encodeQueryComponent("Hello Ladies + Gentlemen, a signed OAuth request!"));
print(Uri.encodeFull("Hello Ladies + Gentlemen, a signed OAuth request!"));
print(Uri.encodeComponent("Hello Ladies + Gentlemen, a signed OAuth request!"));

Output: 输出:

Hello+Ladies+%2B+Gentlemen%2C+a+signed+OAuth+request%21
Hello%20Ladies%20+%20Gentlemen,%20a%20signed%20OAuth%20request!
Hello%20Ladies%20%2B%20Gentlemen%2C%20a%20signed%20OAuth%20request!

The last one ( encodeComponent ) seems the closest, just the exclamation mark is wrong. 最后一个( encodeComponent )似乎是最接近的,只是感叹号是错误的。

Is there an existing method that does this encoding as I require (the same as C#'s EscapeDataString )? 是否有现有的方法可以按照我的要求进行这种编码(与C#的EscapeDataString )?

I can't find a Dart function that is equivalent to C#'s EscapeDataString , however I think I was able to implement one. 我找不到与C#的EscapeDataString等效的Dart函数,但是我认为我能够实现一个。 Feel free to try it and see if you find any issues. 随时尝试,看看是否发现任何问题。

See this Dartpad: https://dartpad.dartlang.org/4336dad4dc0603952a7c2e545cb8726c 看到此Dartpad: https ://dartpad.dartlang.org/4336dad4dc0603952a7c2e545cb8726c

It's based on the fact that the Dart docs says: 它基于Dart文档说的事实:

All characters except uppercase and lowercase letters, digits and the characters -_.!~*'() are percent-encoded.

So the functions I provided adds percent encoding of those specific characters. 因此,我提供的功能增加了这些特定字符的百分比编码。

As I understand it from the C# docs on EscapeDataString it does encode these characters by default whereas no Dart function I could find does that. 据我从EscapeDataString上的C#文档EscapeDataString它默认情况下会对这些字符进行编码,而我找不到的Dart函数EscapeDataString

The convert package works perfectly. convert程序包完美运行。 There was previously a bug causing numbers to be encoded but a fix was merged and released today in 2.0.1. 以前存在一个错误,导致对数字进行编码,但是今天在2.0.1中合并并发布了一个修复程序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM