c# 调用webapi 传参 特殊字符的问题

时间:2023-03-09 01:03:08
c# 调用webapi 传参 特殊字符的问题

最近在做对接数据接口,遇到一些问题,在C#后台写请求webapi的接口,但是传递过程中参数如果有特殊字符,传入过去之后又问题。

需要转换一下,通过System.Web.HttpUtility.UrlEncode(userkey),

userkey 是个临时参数,这个参数需要System.Web.HttpUtility.UrlEncode编码一下。

实例代码:

        /// <summary>
/// 登陆接口
/// </summary>
public static void Login()
{
Common.WriteLogToTxt(_filePath, "----start loading Login function()----");
Console.WriteLine(DateTime.Now.ToLocalTime() + "----start loading Login function()----"); string content = Common.HttpPostJsonAPI(api_login + "?userkey=" + System.Web.HttpUtility.UrlEncode(userkey), ""); Result_Login _result_Login = new Result_Login();
_result_Login = JsonHelper.ParseFromJson<Result_Login>(content);
token = _result_Login.token; Common.WriteLogToTxt(_filePath, "----return token: ----" + token);
Console.WriteLine(DateTime.Now.ToLocalTime() + "----return token: ----" + token); Common.WriteLogToTxt(_filePath, "----end loading Login function()----");
Console.WriteLine(DateTime.Now.ToLocalTime() + "----end loading Login function()----");
}
        /// <summary>
/// 返回json
/// </summary>
/// <param name="uri"></param>
/// <param name="parameters"></param>
/// <param name="token"></param>
/// <returns></returns>
public static string HttpPostJsonAPI(string uri, string parameters, string token = "")
{
byte[] bytes = Encoding.UTF8.GetBytes(parameters);//这里需要指定提交的编码
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
webRequest.Accept = "application/json";
webRequest.Headers.Add("token", token);
webRequest.ContentLength = bytes.Length;
Stream dataStream = webRequest.GetRequestStream();
dataStream.Write(bytes, , bytes.Length);
dataStream.Close(); HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
StreamReader reader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8);
String res = reader.ReadToEnd();
reader.Close();
return res.Trim();
}

js url 编码问题:

encodeURIComponent() 函数

定义和用法 
encodeURIComponent() 函数可把字符串作为 URI 组件进行编码。

语法 
encodeURIComponent(URIstring)

参数  描述  
URIstring  必需。一个字符串,含有 URI 组件或其他要编码的文本。

返回值 
URIstring 的副本,其中的某些字符将被十六进制的转义序列进行替换。

说明 
该方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ' ( ) 。

其他字符(比如 :;/?:@&=+$,# 这些用于分隔 URI 组件的标点符号),都是由一个或多个十六进制的转义序列替换的。

提示和注释 
提示:请注意 encodeURIComponent() 函数 与 encodeURI() 函数的区别之处,前者假定它的参数是 URI 的一部分(比如协议、主机名、路径或查询字符串)。因此 encodeURIComponent() 函数将转义用于分隔 URI 各个部分的标点符号。

示例可参考:http://blog.****.net/zyu67/article/details/43951653

参考资料:

https://www.cnblogs.com/xcsn/archive/2013/05/15/3079373.html