1 如果参数中含有特殊字符&,则强制URL编码<br> 2 3 http协议中参数的传输是"key=value"这种简直对形式的,如果要传多个参数就需要用“&”符号对键值对进行分割。如"?name1=value1&name2=value2",这样在服务端在收到这种字符串的时候,会用“&”分割出每一个参数,然后再用“=”来分割出参数值,
在计算机中使用用ASCII码表示 4 5 如果我的参数值中就包含=或&这种特殊字符的时候该怎么办。 6 比如说“name1=value1”,其中value1的值是“va&lu=e1”字符串,那么实际在传输过程中就会变成这样“name1=va&lu=e1”。我们的本意是就只有一个键值对,但是服务端会解析成两个键值对,这样就产生了歧义。 7 8 URL编码只是简单的在特殊字符的各个字节前加上%,例如,我们对上述会产生奇异的字符进行URL编码后结果:“name1=va%26lu%3D”,这样服务端会把紧跟在“%”后的字节当成普通的字节,就是不会把它当成各个参数或键值对的分隔符。
第一种方法: 第一步:获取在Web.config中配置要请求的地址 string url = System.Web.Configuration.WebConfigurationManager.AppSettings["url"]; 第二步:把字符串编码(编码详解) string allStr = System.Web.HttpUtility.UrlEncode(str, System.Text.Encoding.UTF8) ; 第三步:把参数转成byte byte[] bufferB = Encoding.UTF8.GetBytes(allStr); 第四步:构建HttpWebRequest,并发送 System.Net.ServicePointManager.DefaultConnectionLimit = 200; HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url); WebReq.Method = "POST"; WebReq.ContentType = "application/x-www-form-urlencoded"; WebReq.ContentLength = allStr.Length; Stream PostData = WebReq.GetRequestStream(); PostData.Write(bufferB, 0, bufferB.Length); PostData.Close(); 第五步:接收返回结果(解析返回的JSON) HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse(); StreamReader sr = new StreamReader(WebResp.GetResponseStream(), System.Text.Encoding.UTF8); string backstr = sr.ReadToEnd(); backstr = HttpUtility.UrlDecode(backstr); Console.WriteLine(WebResp.StatusCode); Console.WriteLine(WebResp.Server); Stream Answer = WebResp.GetResponseStream(); StreamReader _Answer = new StreamReader(Answer); Console.WriteLine(_Answer.ReadToEnd()); --------------------- 作者:容妞 来源:CSDN 原文:https://blog.csdn.net/lijingrong_ljr/article/details/53214729 版权声明:本文为博主原创文章,转载请附上博文链接!
string url = "http://16.8.3.91:8089/api/query/Bicycle?deviceno=1&operator=2&sign=9fe789d7a5629a59ed56d7a256dc5a1a&cardno=0310";//http需要传递的参数与地址 WebRequest wRequest = WebRequest.Create(url); wRequest.Method = "GET"; wRequest.ContentType = "text/html;charset=UTF-8"; WebResponse wResponse = wRequest.GetResponse(); Stream stream = wResponse.GetResponseStream(); StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8); string str = reader.ReadToEnd(); //url返回的值 --------------------- 作者:叫我梧桐树 来源:CSDN 原文:https://blog.csdn.net/u012732371/article/details/58587092 版权声明:本文为博主原创文章,转载请附上博文链接!
M1001 m1001 = new M1001() { Head = baseHead, Body = body }; string serviceUrl = "https://jq.asus.com.cn/omsec/v1.0/ECOrder/PutOrder?appid=t0a2YlbyD5JL&token=LLfDDlwHuifVnP2BNngCdebuj4DtYXtAD6QAKEHaA4cDMUniKkKnNJwnuQlL"; Encoding encoding = Encoding.UTF8; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceUrl); request.Method = "POST"; request.Accept = "text/html, application/xhtml+xml, */*"; request.ContentType = "application/json"; byte[] buffer = encoding.GetBytes(JsonConvert.SerializeObject(m1001)); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); HttpWebResponse res = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8)) { string Result = reader.ReadToEnd(); }
异步async
string json = JsonConvert.SerializeObject(m1001); string appid = System.Configuration.ConfigurationManager.AppSettings["appid"]; string token = System.Configuration.ConfigurationManager.AppSettings["token"]; string serviceUrl = "https://xxxxxx?appid=" + appid + "&token=" + token + ""; HttpContent JSONContents = new StringContent(JsonConvert.SerializeObject(m1001), Encoding.UTF8, "application/json"); HttpClient _httpClient = new HttpClient(); var Msg = await _httpClient.PostAsync(serviceUrl, JSONContents); if (Msg.IsSuccessStatusCode) { string Ret = ""; var s = Msg.Content.ReadAsStringAsync(); JObject objs = JObject.Parse(s.Result); Root baseroot = JsonConvert.DeserializeObject<Root>(s.Result); if (string.IsNullOrEmpty(baseroot.head.errorCode)) {//写入成功 Ret = baseroot.body.CreateDateTime.ToString(); } else {//写入失败 Ret = baseroot.head.transMessage.ToString();//发邮件还是怎么的 } }
// 使用C# 5.0中提供的async 和await关键字来定义异步方法 // 从代码中可以看出C#5.0 中定义异步方法就像定义同步方法一样简单。 // 使用async 和await定义异步方法不会创建新线程, // 它运行在现有线程上执行多个任务. // 此时不知道大家有没有一个疑问的?在现有线程上(即UI线程上)运行一个耗时的操作时, // 为什么不会堵塞UI线程的呢? // 这个问题的答案就是 当编译器看到await关键字时,线程会 private async Task<long> AccessWebAsync() { MemoryStream content = new MemoryStream(); // 对MSDN发起一个Web请求 HttpWebRequest webRequest = WebRequest.Create("http://msdn.microsoft.com/zh-cn/") as HttpWebRequest; if (webRequest != null) { // 返回回复结果 using (WebResponse response = await webRequest.GetResponseAsync()) { using (Stream responseStream = response.GetResponseStream()) { await responseStream.CopyToAsync(content); } } } txbAsynMethodID.Text = Thread.CurrentThread.ManagedThreadId.ToString() ; return content.Length; }
string CustomerPO = j["Success"]["items"]["item"][i]["out_tid"].ToString(); string storage_name = com.Switch_ShipTo(j["Success"]["items"]["item"][i]["storage_id"].ToString());// 要做个仓库编码匹配仓库名称的设置 string tid_item = j["Success"]["items"]["item"][i]["tid_item"].ToString();//明细 string pro_totalfee = j["Success"]["items"]["item"][i]["pro_totalfee"].ToString();//产品总金额 JArray jArray = JArray.Parse(tid_item); JArray arr = new JArray(); for (int q = 0; q < jArray.Count; q++) { JObject obj = new JObject(); JObject jdata = (JObject)jArray[q]; obj["linenum"] = jdata["pro_detail_code"]; obj["sku"] = jdata["product_no"].ToString();// obj["originalsku"] = jdata["product_no"].ToString();//先在ebd里查询不到 obj["qty"] = jdata["pro_num"].ToString(); //edbProductGet(jdata["product_no"].ToString()); obj["inventoryname"] = com.Switch_ShipTo(jdata["storage_id"].ToString()); obj["price"] = com.Change(Convert.ToDouble(pro_totalfee) / jArray.Count, 2); arr.Add(obj); } var data = new JObject { {"Head",new JObject { {"TransCode","X1002" }, {"TransId",com.GenerateTransId(18)} } }, { "Body", new JObject { {"orderno", orderno }, {"CustomerPO", CustomerPO}, {"ordertypecode", "Direct" }, {"billto", _Setting.Value.JD_billto.ToString() },//账款店铺是不是要写为定值 {"shipto", storage_name},//还有就是shipto,目前是8个仓,但是从e店宝获取的只是storage_id,是要把对应的仓库名称写在配置里,还是只传id值 {"workid", _Setting.Value.JD_workid.ToString()}, //workid {"detail", arr } } } }; string appid = _Setting.Value.Gettoken_appid;//这个是要替换成正式的appid(有了) var httpClient = new HttpClient(); string serviceUrl = "https://xxxcn:9007/api/v1.0/Order/PutStandard?appid=" + appid + "&token=" + com.GetNewToken() + "";//这个是写入京东的url HttpContent JSONContents = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json"); var message = await httpClient.PostAsync(serviceUrl, JSONContents); if (message.IsSuccessStatusCode) { string rr = await message.Content.ReadAsStringAsync(); JObject objs = JObject.Parse(rr); string errorCode = objs["head"]["errorCode"].ToString(); if (string.IsNullOrEmpty(errorCode)) {//写入成功 } else {//写入失败 com.JD_Error("订单:" + orderno + ",写入StageHead表失败:" + objs["head"]["transMessage"].ToString()); } } //using (var resss = await httpClient.PostAsync(serviceUrl, JSONContents)) //{ // if (resss.IsSuccessStatusCode) // { // string ser = $"{resss.Content.ReadAsStringAsync().Result}"; // JObject objs = JObject.Parse(ser); // string errorCode = objs["head"]["errorCode"].ToString(); // if (string.IsNullOrEmpty(errorCode)) // {//写入成功 // } // else // {//写入失败 // com.JD_Error("订单:" + orderno + ",写入StageHead表失败:" + objs["head"]["transMessage"].ToString()); // } // } //}
1 //string appid = _Setting.Value.Gettoken_appid;//这个是要替换成正式的appid(有了) 2 //string serviceUrl = "https://xxxx.com.cn:9007/api/v1.0/Order/PutStandard?appid=" + appid + "&token=" + com.GetNewToken() + "";// 3 //Encoding encoding = Encoding.UTF8; 4 //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceUrl); 5 //request.Method = "POST"; 6 //request.Accept = "text/html, application/xhtml+xml, */*"; 7 //request.ContentType = "application/json"; 8 //byte[] buffer = encoding.GetBytes(JsonConvert.SerializeObject(data)); 9 //request.ContentLength = buffer.Length; 10 //request.GetRequestStream().Write(buffer, 0, buffer.Length); 11 //HttpWebResponse res = (HttpWebResponse)request.GetResponse(); 12 //using (StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8)) 13 //{ 14 // string Result = reader.ReadToEnd(); 15 // JObject objs = JObject.Parse(Result); 16 // string errorCode = objs["head"]["errorCode"].ToString(); 17 // if (string.IsNullOrEmpty(errorCode)) 18 // {//写入成功 19 // } 20 // else 21 // {//写入失败 22 // com.JD_Error("订单:" + orderno + ",写入StageHead表失败:" + objs["head"]["transMessage"].ToString()); 23 // } 24 //}
Header中加参数
public static async Task<string> ValidateToken(string URL, string HeadersPara) { try { HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("Authorization", HeadersPara); var token= await httpClient.PostAsync(URL, null);//body中没有传值,用null替代 if (token.IsSuccessStatusCode) { var s = token.Content.ReadAsStringAsync(); var j = JObject.Parse(s.Result); var rettoken = j["DATA"]["TOKEN"].ToString(); return rettoken; } else { throw new Exception("StatusCode:" + token.StatusCode.ToString()); } } catch (Exception) { throw; } }