LoginSignup
0
0

More than 5 years have passed since last update.

PowerShellでパーセントエンコーディング

Last updated at Posted at 2017-04-04

パーセントエンコーディングとは

httpプロトコルでPOSTやGETするときにURIに使える文字が決まっています.
なので使えない文字は16進数に変換して,文字の前に%をつけることて,利用する必要があります.この変換を文字列に行うのがパーセントエンコーディングです.

.NET Frameworkでのパーセントエンコーディング

Uri.EscapeDataString というメソッドでできることになっているのですが,version 4.0だと、RFC2396.version 4.5 だと RFC3986.それぞれ違う規約によってエンコーディングされるようです.私の環境のPowerShellの.NET Frameworkのversionは4.0なので,RFC2396にエンコードされます.しかし今回私はtwitterのAPIの利用がしたかったので,それに必要なRFC3986にエンコードする関数を制作しました.

function EncordString ([System.String]$inputstring) {
    #RFC3986でパーセントエンコーディング
    $inputchars=[System.Text.Encoding]::GetEncoding("utf-8").GetBytes($inputstring)
    #元の文字列のエンコードがUTF-8以外の場合はそのエンコードに書き換えてください.
    $encorded=New-Object System.Text.StringBuilder
    foreach($ch in $inputchars)
    {
        if((0x30-le$ch-and$ch-le0x39)`
        -or (0x41 -le $ch -and $ch -le 0x5A)`
        -or (0x61 -le $ch -and $ch -le 0x7A)`
        -or (0x2D -eq $ch -or 0x2E -eq $ch`
        -or 0x5F -eq $ch -or 0x7E -eq $ch))
        #'0'以上'9'未満
        #'A'以上'Z'未満
        #'a'以上'z'未満
        #その他使用できる文字(‘-‘, ‘.’, ‘_’, ‘~’)
        {
            [void]$encorded.Append([System.Convert]::ToChar($ch))
        }else {
            [void]$encorded.Append("%{0:X2}" -f [int]$ch)   
        }
    }
    $encorded.ToString()
}

参考文献

Percent encoding parameters
https://dev.twitter.com/oauth/overview/percent-encoding-parameters
URLエンコード、URLデコードを行う
http://dobon.net/vb/dotnet/internet/urlencode.html
[C#] string(文字列)からバイト型配列 byte に変換する
https://www.ipentec.com/document/document.aspx?page=csharp-string-to-bytearray&culture=ja-jp

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0