如何逃避POST HttpWebRequest的使用URL编码数据 [英] How to escape URL-encoded data in POST with HttpWebRequest

查看:398
本文介绍了如何逃避POST HttpWebRequest的使用URL编码数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个URL编码后发送到PHP实现一个REST API。 POST数据包含两个用户提供的字符串:

  WebRequest的要求= HttpWebRequest.Create(新的URI(serverUri,休息) ); 
request.Method =POST;
request.ContentType =应用/的X WWW的形式了urlencoded;字符集= UTF-8;
request.Headers.Add(内容传输编码,二进制);

//形式的URL编码的凭据,我们将使用登录
StringBuilder的建设者=新的StringBuilder();
builder.Append(用户=);
builder.Append(用户);
builder.Append(与&密码=);
builder.Append(密码);
字节[] =凭证Encoding.UTF8.GetBytes(builder.ToString());

//写URL编码后的数据到请求流。
request.ContentLength = credentials.Length;
使用(流requestStream = request.GetRequestStream()){
requestStream.Write(凭据,0,credentials.Length);
}

这发送一个HTTP请求,其中包含用户服务器=名为myusername&放大器;密码=输入mypassword 在UTF-8作为其POST数据



我怎样才能逃避用户提供的字符串。?
为例,如果我有一个名为user 大和放大器;平均,应该怎么连字符转义以便它不会弄乱请求行

解决方案

您可以使用静态 HttpUtility 类的System.Web中的编码和解码HTML和网址相关的值。



尝试 HttpUtility.UrlEncode()


I am trying to send an URL-encoded post to a REST API implemented in PHP. The POST data contains two user-provided strings:

WebRequest request = HttpWebRequest.Create(new Uri(serverUri, "rest"));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
request.Headers.Add("Content-Transfer-Encoding", "binary");

// Form the url-encoded credentials we'll use to log in
StringBuilder builder = new StringBuilder();
builder.Append("user=");
builder.Append(user);
builder.Append("&password=");
builder.Append(password);
byte[] credentials = Encoding.UTF8.GetBytes(builder.ToString());

// Write the url-encoded post data into the request stream.
request.ContentLength = credentials.Length;
using (Stream requestStream = request.GetRequestStream()) {
  requestStream.Write(credentials, 0, credentials.Length);
}

This sends a HTTP request to the server containing user=myusername&password=mypassword in UTF-8 as its POST data.

How can I escape the user-provided strings? For example, if I had a user named big&mean, how should the ampersand be escaped so that it does not mess up the request line?

解决方案

You can use the static HttpUtility class in System.Web for encoding and decoding HTML and Url related values.

Try HttpUtility.UrlEncode().

这篇关于如何逃避POST HttpWebRequest的使用URL编码数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆