c#后台獲取asxh的返回數據,后台創建一個請求實例,獲取請求實例的返回值
public string GetResponseByPost(string apiUrl, string queryString) { string responseString = string.Empty; HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(apiUrl + queryString); request.ContentType = "text/html"; request.Method = "POST"; request.ContentLength = queryString.Length; request.Timeout = 20000; byte[] bytes = Encoding.UTF8.GetBytes(queryString); Stream os = null; try { // send the Post request.ContentLength = bytes.Length; //Count bytes to send os = request.GetRequestStream(); os.Write(bytes, 0, bytes.Length); //Send it } catch (WebException ex) { throw ex; } finally { if (os != null) { os.Close(); } } HttpWebResponse response = null; try { response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { responseString = reader.ReadToEnd(); } } catch (Exception ex2) { throw ex2; } finally { if (response != null) response.Close(); } return responseString; }
程序員的基礎教程:菜鳥程序員