0

C#アプリケーションからRubyAPIと通信しようとすると問題が発生します。

パラメータ名が「data」のJSONデータをPOSTする必要がありますが、APIは次のように返します:'!! リクエストの処理中に予期しないエラーが発生しました:無効な%-encoding'。

Content-Typeを「application/json」および「application/x-www-form-urlencoded」に設定してみました。charset =utf-8'。

私のPOSTデータは次のようになります'data=some_json_string'。

json文字列をエスケープする必要があると思います。それが私の問題である場合、サードパーティのライブラリを使用せずに.NETでそれを行うにはどうすればよいですか?

コード:

        byte[] data = System.Text.ASCIIEncoding.UTF8.GetBytes(sdata);

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url, UriKind.Absolute));

        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
        request.ContentLength = data.Length;

        Stream reqStream = request.GetRequestStream();

        // Send the data.
        reqStream.Write(data, 0, data.Length);
        reqStream.Close();

前もって感謝します!

4

1 に答える 1

0

入ってくる文字列sdataがすでにJSON形式であると仮定すると、次のことができます。

using (WebClient wc = new WebClient())
{
    string uri = "http://www.somewhere.com/somemethod";
    string parameters = "data=" + Uri.EscapeDataString(sdata);
    wc.Headers["Content-type"] = "application/x-www-form-urlencoded";
    string result = wc.UploadString(uri, parameters);
}

Depending on the consuming service it may need the Content-type set to application/json?

于 2012-07-13T19:12:36.557 に答える