最近在做對接數據接口,遇到一些問題,在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, 0, 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.csdn.net/zyu67/article/details/43951653
參考資料:
https://www.cnblogs.com/xcsn/archive/2013/05/15/3079373.html