【问题标题】:utf-8 character url both in c# webrequest and browser not workc# webrequest 和浏览器中的 utf-8 字符 url 都不起作用
【发布时间】:2016-11-07 06:54:56
【问题描述】:

我正在尝试通过 LAN 电缆和 WebRequest 向机器发送一些数据 这是我正在使用的课程

public class MyWebRequest
{
    private WebRequest request;
    private Stream dataStream;

    private string status;

    public String Status
    {
        get
        {
            return status;
        }
        set
        {
            status = value;
        }
    }

    public MyWebRequest(string url)
    {

        request = WebRequest.Create(url);
    }

    public MyWebRequest(string url, string method)
        : this(url)
    {

        if (method.Equals("GET") || method.Equals("POST"))
        {
            request.Method = method;
        }
        else
        {
            throw new Exception("Invalid Method Type");
        }
    }

    public MyWebRequest(string url, string method, string data)
        : this(url, method)
    {

        string postData = data;
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);

        request.ContentType = "application/x-www-form-urlencoded";

        // Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;

        dataStream = request.GetRequestStream();

        dataStream.Write(byteArray, 0, byteArray.Length);

        dataStream.Close();

    }

    public string GetResponse()
    {
        WebResponse response = request.GetResponse();

        this.Status = ((HttpWebResponse)response).StatusDescription;

        dataStream = response.GetResponseStream();

        StreamReader reader = new StreamReader(dataStream);

        string responseFromServer = reader.ReadToEnd();

        reader.Close();
        dataStream.Close();
        response.Close();

        return responseFromServer;
    }

}

动作代码是

    command="?insert_employee:cart_number=0007989222&name=علي&last_name=رمضاني&finger_number=123&?";
MyWebRequest wr = new MyWebRequest(command, "GET");
string Response = wr.GetResponse();

如您所见,我的命令中有一些 utf-8 字符,它在浏览器和我的应用程序中都不起作用 但是当我尝试这个字符串时它完美地工作:

command = "?insert_employee:cart_number=0007989222&name=ali&last_name=ramazani&finger_number=123&?"

我测试了我在 stackoverflow 中找到的许多方法,例如“使用 uri 而不是 url”、“使用 httpUtility.UrlEncode”……但它们都不是有效的,或者我可能以错误的方式使用它们。

你有什么帮忙的想法吗?

【问题讨论】:

    标签: c# url utf-8 webrequest


    【解决方案1】:

    您可以使用 HttpUtility.UrlPathEncode 方法对 URL 的路径部分进行编码,以保证解码后的 URL 一致,无论哪个平台或浏览器执行解码。

    Encoding有很好的解释

    urlPrueba = "http://someexample.com/?insert_employee:cart_number=0007989222&name=علي&last_name=رمضاني&finger_number=123&?";
    var uri = new Uri(urlPrueba);
    Console.WriteLine("urlPrueba" + " = " + uri.AbsoluteUri);
    

    【讨论】:

    • uri 也没有帮助我
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-03
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 2017-04-20
    相关资源
    最近更新 更多