C# Escape Plus Sign (+) in POST using HttpWebRequest

人盡茶涼 提交于 2019-12-02 12:21:01

I'd recommend you a WebClient. Will shorten your code and take care of encoding and stuff:

using (var client = new WebClient())
{
    var values = new NameValueCollection
    { 
        { "username", "anyname" },
        { "password", "+13Gt2" },
    };
    var url = "http://foo.com";
    var result = client.UploadValues(url, values);
}
WhySoSerious

I found my answer using Uri.EscapeDataString it exactly solved my problem, but somehow I couldn't do it with HttpUtility.UrlEncode. Stackoverflowing around, I found this question that is about urlEncode method, in msdn it documentation tells that:

Encodes a URL string.

But I know now that is wrong if used to encode POST data (@Marvin, @Polity, thanks for the correction). After discarding it, I tried the following:

string postData = String.Format("username={0}&password={1}", "anyname", Uri.EscapeDataString("+13Gt2"));

The POST data is converted into:

// **Output
string username = anyname;
string password = %2B13Gt2;

Uri.EscapeDataString in msdn says the following:

Converts a string to its escaped representation.

I think this what I was looking for, when I tried the above, I could POST correctly whenever there's data including the '+' characters in the formdata, but somehow there's much to learn about them.

This link is really helpful.

http://blogs.msdn.com/b/yangxind/archive/2006/11/09/don-t-use-net-system-uri-unescapedatastring-in-url-decoding.aspx

Thanks a lot for the answers and your time, I appreciate it very much. Regards mates.

the postdata you are sending should NOT be URL encoded! it's formdata, not the URL

  string url = @"http://localhost/WebApp/AddService.asmx/Add";
  string postData = "x=6&y=8";

  WebRequest req = WebRequest.Create(url);
  HttpWebRequest httpReq = (HttpWebRequest)req;

  httpReq.Method = WebRequestMethods.Http.Post;
  httpReq.ContentType = "application/x-www-form-urlencoded";
  Stream s = httpReq.GetRequestStream();
  StreamWriter sw = new StreamWriter(s,Encoding.ASCII);
  sw.Write(postData);
  sw.Close();

  HttpWebResponse httpResp = 
                 (HttpWebResponse)httpReq.GetResponse();
  s = httpResp.GetResponseStream();
  StreamReader sr = new StreamReader(s, Encoding.ASCII);
  Console.WriteLine(sr.ReadToEnd());

This uses the System.Text.Encoding.ASCII to encode the postdata.

Hope this helps,

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!