private string webCheckSessionSSO(String url, String operation, String idsessioneSSO, String idsessioneSSOASPNET) { try { System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }; String param = "Operation=" + operation + "&IdSessioneSSO=" + idsessioneSSO + "&IdSessioneASPNET=" + idsessioneSSOASPNET; byte[] dataStream = System.Text.Encoding.UTF8.GetBytes(param); Uri urlcheck = new System.Uri(url); System.Net.HttpWebRequest client = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(urlcheck); client.Method = "POST"; client.ContentType = "application/x-www-form-urlencoded"; client.ContentLength = dataStream.Length; client.GetRequestStream().Write(dataStream, 0, dataStream.Length); client.GetRequestStream().Close(); System.IO.StreamReader sr = new System.IO.StreamReader(client.GetResponse().GetResponseStream()); String ret = sr.ReadToEnd(); sr.Close(); return(ret); } catch (Exception ex) { return("<AUTH>NO</AUTH>"); } }
/// <summary> /// 创建HttpWebResponse请求对象 /// </summary> /// <param name="url">请求网址</param> /// <param name="method">请求动作</param> /// <param name="postData">POST数据</param> /// <returns></returns> private System.Net.HttpWebResponse HttpWebResponse(string url, string postData = "", string name = "", string filePath = "") { try { System.Net.HttpWebRequest hwr = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); hwr.Timeout = Timeout; hwr.Method = Method.ToString(); if (Method.ToString().ToUpper() == "POST") { if (ContentType.ToString().ToUpper() == "DATA") { //POST 文件 string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线 byte[] item_boundary_bytes = Encoding.UTF8.GetBytes(string.Format("\r\n--{0}\r\n", boundary)); // 开始boundary byte[] post_header_bytes = Encoding.UTF8.GetBytes(StringBuilderHeader(name, filePath)); // 头部boundary byte[] file_bytes = FileBytes(filePath); // 文件byte byte[] post_data = StrToByte(postData); // 内容byte byte[] end_boundary_bytes = Encoding.UTF8.GetBytes(string.Format("\r\n--{0}--\r\n", boundary)); // 结束boundary hwr.ContentType = string.Format("multipart/form-data;charset=utf-8;boundary={0}", boundary); System.IO.Stream post_stream = hwr.GetRequestStream(); post_stream.Write(item_boundary_bytes, 0, item_boundary_bytes.Length); post_stream.Write(post_header_bytes, 0, post_header_bytes.Length); post_stream.Write(file_bytes, 0, file_bytes.Length); post_stream.Write(post_data, 0, post_data.Length); post_stream.Write(end_boundary_bytes, 0, end_boundary_bytes.Length); post_stream.Close(); } else { //POST 字符串 byte[] post_data = StrToByte(postData); hwr.ContentType = GetContentType(ContentType); hwr.ContentLength = post_data.Length; System.IO.Stream newStream = hwr.GetRequestStream(); newStream.Write(post_data, 0, post_data.Length); //设置POST newStream.Close(); } } System.Net.HttpWebResponse hwrs = (System.Net.HttpWebResponse)hwr.GetResponse(); return(hwrs); } catch (Exception ex) { throw new Exception(ex.Message); } }
public static string SendPostStr(string url, string postString) { if (string.IsNullOrEmpty(url)) { return(""); } byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postString); System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); httpWebRequest.Method = "POST"; //httpWebRequest.ContentType = "text/xml"; httpWebRequest.ContentType = "application/json; charset=utf-8"; // httpWebRequest.ContentLength = Encoding.UTF8.GetByteCount(data); //strJson为json字符串 System.IO.Stream stream = httpWebRequest.GetRequestStream(); stream.Write(postBytes, 0, postBytes.Length); stream.Close(); var response = httpWebRequest.GetResponse(); System.IO.Stream streamResponse = response.GetResponseStream(); System.IO.StreamReader streamRead = new System.IO.StreamReader(streamResponse); String responseString = streamRead.ReadToEnd(); return(responseString); }
/// <summary> /// Post 数据至接口端函数 /// </summary> /// <param name="postContent">提交内容</param> /// <param name="url">提交地址</param> /// <returns></returns> private string PostHttp(string postContent, string url) { string resultstr = string.Empty; System.Text.Encoding encode = System.Text.Encoding.GetEncoding("gb2312"); System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); req.Method = "POST"; req.ContentType = "text/xml"; req.Timeout = 1000000; Byte[] bytes = encode.GetBytes(postContent); req.ContentLength = bytes.Length; Stream sendStream = req.GetRequestStream(); sendStream.Write(bytes, 0, bytes.Length); sendStream.Close(); System.Net.WebResponse rep = req.GetResponse(); Stream getStream = rep.GetResponseStream(); using (StreamReader sr = new StreamReader(getStream, Encoding.UTF8)) { resultstr = sr.ReadToEnd(); sr.Close(); } getStream.Close(); rep.Close(); return(resultstr); }
static void Main(string[] args) { string cid = "OCBC"; string strId = "admin"; string strPassword = "******"; string postData = "<?xml version='1.0' encoding='iso-8859-1'?><!DOCTYPE jds SYSTEM '/home/httpd/html/dtd/jds2.dtd'><jds><account acid='" + cid + "'loginid='" + strId + "' passwd='" + strPassword + "'>{0}</account></jds>"; //string postData = "<account acid='" + cid + "'loginid='" + strId + "' passwd='" + strPassword + "'><change_pwd>NEW_PASSWORD</change_pwd></account>"; Encoding encoding = Encoding.UTF8; byte[] data = encoding.GetBytes(postData); System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create("https://smsmgr.three.com.mo/servlet/corpsms.jdsXMLClient2"); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; req.ContentType = "text/XML";//SOAP req.ContentLength = data.Length; System.IO.Stream newStream = req.GetRequestStream(); // 发送数据 newStream.Write(data, 0, data.Length); System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)req.GetResponse(); MessageBox.Show(res.StatusDescription.ToString()); newStream.Close(); //// 获取响应 HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse(); StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); string content = reader.ReadToEnd(); }
public static Stream ProcessCommand(string strURI, string strHttpCommand, string strContent) { try { byte[] arr = System.Text.Encoding.UTF8.GetBytes(strContent); Uri address = new Uri(strURI); System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(address); request.Method = strHttpCommand; request.ContentType = "application/json"; request.ContentLength = arr.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(arr, 0, arr.Length); dataStream.Close(); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); return(response.GetResponseStream()); } catch (System.Net.WebException webex) { throw new Exception(webex.Message); } catch (Exception Ex) { throw new Exception(Ex.Message); } }
/// <summary> /// 向服务器 POST 数据 /// </summary> /// <param name="result">接收返回内容</param> /// <param name="postUrl">服务器地址</param> /// <param name="paramData">数据(eg: "键=值&name=Kity",注意值部份需用 string System.Web.HttpUtility.UrlPathEncode(string) 进行编码)</param> /// <param name="dataEncode">参数编码(eg: System.Text.Encoding.UTF8)</param> /// <returns>请求成功则用服务器返回内容填充result, 否则用异常消息填充</returns> public static bool PostWebRequest(out string result, string postUrl, string paramData, System.Text.Encoding dataEncode) { try { byte[] byteArray = dataEncode.GetBytes(paramData); //转化 System.Net.HttpWebRequest webReq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new Uri(postUrl)); //webReq.ProtocolVersion = new Version("1.0"); //webReq.UserAgent = ""; //webReq.CookieContainer = new System.Net.CookieContainer(); webReq.Method = "POST"; webReq.ContentType = "application/x-www-form-urlencoded"; webReq.ContentLength = byteArray.Length; System.IO.Stream newStream = webReq.GetRequestStream(); newStream.Write(byteArray, 0, byteArray.Length); newStream.Close(); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)webReq.GetResponse(); System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream(), dataEncode); result = sr.ReadToEnd(); sr.Close(); response.Close(); newStream.Close(); } catch (Exception ex) { result = ex.Message; return(false); } return(true); }
/// <summary> /// 发表一条微博 /// </summary> /// <param name="url">API地址 /// http://api.t.sina.com.cn/statuses/update.json /// </param> /// <param name="data">AppKey和微博内容 /// "source=123456&status=" + System.Web.HttpUtility.UrlEncode(微博内容); /// </param> /// <returns></returns> internal static bool PostBlog(string url, string data) { try { System.Net.WebRequest webRequest = System.Net.WebRequest.Create(url); System.Net.HttpWebRequest httpRequest = webRequest as System.Net.HttpWebRequest; System.Net.CredentialCache myCache = new System.Net.CredentialCache(); myCache.Add(new Uri(url), "Basic", new System.Net.NetworkCredential(UserInfo.UserName, UserInfo.PassWord)); httpRequest.Credentials = myCache; httpRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String( new System.Text.ASCIIEncoding().GetBytes(UserInfo.UserName + ":" + UserInfo.PassWord))); httpRequest.Method = "POST"; httpRequest.ContentType = "application/x-www-form-urlencoded"; System.Text.Encoding encoding = System.Text.Encoding.UTF8; //System.Text.Encoding.ASCII byte[] bytesToPost = encoding.GetBytes(data); //System.Web.HttpUtility.UrlEncode(data) httpRequest.ContentLength = bytesToPost.Length; System.IO.Stream requestStream = httpRequest.GetRequestStream(); requestStream.Write(bytesToPost, 0, bytesToPost.Length); requestStream.Close(); return(true); } catch { return(false); } }
protected string TranslateCore( string text, string sourceLanguageCode, string desinationLanguageCode) { Uri serviceUri = new Uri("http://ajax.googleapis.com/ajax/services/language/translate"); UTF8Encoding encoding = new UTF8Encoding(); string postData = "v=1.0"; postData += ("&q=" + text.XMLEncode()); postData += ("&langpair=" + sourceLanguageCode + "|" + desinationLanguageCode); byte[] data = encoding.GetBytes(postData); System.Net.HttpWebRequest httpRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(serviceUri); httpRequest.Timeout = 15000; httpRequest.Method = "POST"; httpRequest.ContentType = "application/x-www-form-urlencoded; charset=utf-8"; httpRequest.ContentLength = data.Length; using (Stream requestStream = httpRequest.GetRequestStream()) { requestStream.Write(data, 0, data.Length); } System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)httpRequest.GetResponse(); String resp = null; using (StreamReader sReader = new StreamReader(response.GetResponseStream(), encoding)) { resp = sReader.ReadToEnd(); } return(resp); }
public static string WebPagePostGet(string url, string data, Encoding code) { try { System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; byte[] byte1 = Encoding.UTF8.GetBytes(data); request.ContentLength = byte1.Length; Stream newStream = request.GetRequestStream(); // Send the data. newStream.Write(byte1, 0, byte1.Length); //写入参数 newStream.Close(); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); Encoding coding = code; System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), coding); string s = reader.ReadToEnd(); reader.Close(); reader.Dispose(); response.Close(); reader = null; response = null; request = null; return(s); } catch (Exception e) { return("ERROR"); } }
private void Login(System.Net.IWebProxy proxy) { if (cookie == null) { //System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://www.secure.pixiv.net/login.php"); System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://www.pixiv.net/login.php"); req.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"; req.Proxy = proxy; req.Timeout = 8000; req.Method = "POST"; //prevent 302 req.AllowAutoRedirect = false; //user & pass int index = rand.Next(0, user.Length); string data = "mode=login&pixiv_id=" + user[index] + "&pass="******"&skip=1"; byte[] buf = Encoding.UTF8.GetBytes(data); req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = buf.Length; System.IO.Stream str = req.GetRequestStream(); str.Write(buf, 0, buf.Length); str.Close(); System.Net.WebResponse rsp = req.GetResponse(); //HTTP 302然后返回实际地址 cookie = rsp.Headers.Get("Set-Cookie"); if (/*rsp.Headers.Get("Location") == null ||*/ cookie == null) { throw new Exception("自动登录失败"); } //Set-Cookie: PHPSESSID=3af0737dc5d8a27f5504a7b8fe427286; expires=Tue, 15-May-2012 10:05:39 GMT; path=/; domain=.pixiv.net int sessionIndex = cookie.LastIndexOf("PHPSESSID"); cookie = cookie.Substring(sessionIndex, cookie.IndexOf(';', sessionIndex) - sessionIndex); rsp.Close(); } }
private static bool OptimizeImage(string originalFile, string newFile, OptimusAction action, out string error) { error = null; try { string url = string.Format("https://api.optimus.io/{0}?{1}", licenceKey, action); System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); req.ContentType = "application/x-www-form-urlencoded"; req.Method = "POST"; req.UserAgent = "Optimus-API"; req.Accept = "image/*"; byte[] bytes = System.IO.File.ReadAllBytes(originalFile); req.ContentLength = bytes.Length; using (System.IO.Stream stream = req.GetRequestStream()) { stream.Write(bytes, 0, bytes.Length); } using (System.IO.Stream input = req.GetResponse().GetResponseStream()) using (System.IO.Stream output = System.IO.File.OpenWrite(newFile)) { input.CopyTo(output); } } catch (System.Net.WebException ex) { error = ex.Message + (ex.InnerException != null ? "\r\n" + ex.InnerException.Message : ""); return(false); } catch (Exception ex) { error = ex.Message + (ex.InnerException != null ? "\r\n" + ex.InnerException.Message : ""); return(false); } return(true); }
private void AddToDb(PatientModel newPatient) { System.Net.HttpWebRequest httpReq = System.Net.WebRequest.CreateHttp("http://localhost:5000/api/icuoccupancy"); httpReq.Method = "POST"; httpReq.ContentType = "application/json"; DataContractJsonSerializer filterDataJsonSerializer = new DataContractJsonSerializer(typeof(PatientModel)); filterDataJsonSerializer.WriteObject(httpReq.GetRequestStream(), newPatient); try { System.Net.HttpWebResponse response = httpReq.GetResponse() as System.Net.HttpWebResponse; // MessageBox.Show($"{response.StatusCode}"); MessageBox.Show("Patient Registered Successfully"); Id.Text = ""; Name.Text = ""; Age.Text = ""; Bedno.Text = ""; //IcuId = icuid.Text, Contact.Text = ""; } catch (Exception) { //MessageBox.Show($"{ exception.Message}"); MessageBox.Show("Please Ensure Correct Deatils of Patient ID And BedNo"); } }
public string ChangeHtml(int level, string originalHtml, System.Net.WebHeaderCollection request, System.Net.WebHeaderCollection response, string pageurl) { string data = pageurl; if (!data.Contains("?")) { throw new Exception("请输入正确的网址"); } data = data.Split('?')[1]; System.Net.HttpWebRequest hwr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create("http://www.qihoo.com/search/getSnap"); hwr.Method = "POST"; hwr.Referer = "http://www.qihoo.com/"; hwr.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; hwr.ServicePoint.Expect100Continue = false; byte[] binarydata = System.Text.Encoding.UTF8.GetBytes(data); hwr.ContentLength = binarydata.Length; hwr.AllowWriteStreamBuffering = true; System.IO.Stream sw = hwr.GetRequestStream(); sw.Write(binarydata, 0, binarydata.Length); if (sw != null) { sw.Close(); } System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)hwr.GetResponse(); byte[] bt = new byte[res.ContentLength]; System.IO.StreamReader sr = new System.IO.StreamReader(res.GetResponseStream(), System.Text.Encoding.UTF8); return(sr.ReadToEnd()); }
/// <summary> /// Send POST HttpRequest /// </summary> /// <param name="requestUrl"></param> /// <param name="requestBody"></param> /// <returns></returns> private static string POSTEoopHttpRequest(string requestUrl, string requestBody) { requestUrl = HttpUtility.UrlDecode(requestUrl, Encoding.UTF8); byte[] data = Encoding.UTF8.GetBytes(requestBody); System.Net.HttpWebRequest myRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(requestUrl); myRequest.Method = "POST"; string language = Thread.CurrentThread.CurrentCulture.Name; myRequest.Headers.Set(System.Net.HttpRequestHeader.AcceptLanguage, Thread.CurrentThread.CurrentCulture.Name); myRequest.Timeout = 8000; myRequest.ContentType = "application/json;charset=UTF-8"; myRequest.Accept = "application/json;charset=UTF-8"; myRequest.ContentLength = data.Length; System.IO.Stream newStream = myRequest.GetRequestStream(); newStream.Write(data, 0, data.Length); newStream.Close(); System.Net.HttpWebResponse myResponse = (System.Net.HttpWebResponse)myRequest.GetResponse(); System.IO.StreamReader reader = new System.IO.StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); string result = reader.ReadToEnd(); result = result.Replace("\r", "").Replace("\n", "").Replace("\t", ""); int status = (int)myResponse.StatusCode; reader.Close(); return(result); }
private string DTDBCall() { string str_C2DCheckAddressUrl = "http://dbs.datatree.com/dtdbxml/service/"; System.Net.HttpWebRequest httpRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(str_C2DCheckAddressUrl); string strQuery = GetDTDBAddress("4206-006-022", "", "", "", "CA", "Los Angeles", true); byte[] reqPostBuffer = System.Text.Encoding.UTF8.GetBytes(strQuery); httpRequest.Method = "POST"; httpRequest.ContentType = "text/xml"; httpRequest.ContentLength = reqPostBuffer.Length; System.IO.Stream reqPostData = httpRequest.GetRequestStream(); reqPostData.Write(reqPostBuffer, 0, reqPostBuffer.Length); reqPostData.Close(); System.IO.StreamReader streamReader = new System.IO.StreamReader(httpRequest.GetResponse().GetResponseStream()); string strResponse = streamReader.ReadToEnd(); System.Xml.XmlDocument xmlforNameCollection = new System.Xml.XmlDocument(); xmlforNameCollection.XmlResolver = null; xmlforNameCollection.LoadXml(strResponse); System.Xml.XmlNodeList propertyInformation = xmlforNameCollection.GetElementsByTagName("_TRANSACTION_HISTORY"); //string Instrument = propertyInformation[0].Attributes["_FormattedSaleDocumentNumberIdentifier"].Value; //string[] Instrumentvalues = Instrument.Split('.'); //string Instrumentresult = InstrumentRequest(Instrumentvalues[0].ToString(), Instrumentvalues[1].ToString()); return(null); }
private static string PostData(string urlstring, Dictionary <string, string> parameters) { string data = GetSendData(parameters); string result = ""; try { System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(urlstring); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(data); webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.ContentLength = buffer.Length; using (Stream strm = webRequest.GetRequestStream()) { strm.Write(buffer, 0, buffer.Length); } System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)webRequest.GetResponse(); using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream())) { result = reader.ReadToEnd(); int iPos = result.IndexOf("{"); if (iPos > 0) { result = result.Substring(iPos); } } return(result); } catch (Exception e) { return("{\"error\":100,\"message\":\"" + e.Message + "\"}"); } }
static void Main(string[] args) { string post2; for (int i = 111; i < 222; i++) { post2 = i.ToString(); System.Net.HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://google.com"); request.Method = "POST"; request.KeepAlive = true; request.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0"; request.ContentType = "application/x-www-form-urlencoded"; request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; request.ServicePoint.Expect100Continue = false; string postData = post2; byte[] byteArray = Encoding.UTF8.GetBytes(postData); request.ContentLength = byteArray.Length; // You need to close the request stream when you're done writing to it. using (Stream dataStream = request.GetRequestStream()) { dataStream.Write(byteArray, 0, byteArray.Length); Console.WriteLine(post2); } // Even if you don't need the response, you still need to close it. request.GetResponse().Close(); } }
private dynamic GetJsonResult(string url, string postData) { System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); if (!string.IsNullOrEmpty(postData)) { request.Method = "POST"; request.ContentType = "application/json-rpc"; request.ContentLength = postData.Length; System.IO.Stream writeStream = request.GetRequestStream(); UTF8Encoding encoding = new UTF8Encoding(); byte[] bytes = encoding.GetBytes(postData); writeStream.Write(bytes, 0, bytes.Length); writeStream.Close(); } System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); System.IO.Stream responseStream = response.GetResponseStream(); if (responseStream != null) { System.IO.StreamReader readStream = new System.IO.StreamReader(responseStream, Encoding.UTF8); var jsonString = readStream.ReadToEnd(); readStream.Close(); responseStream.Close(); response.Close(); var json = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize <dynamic>(jsonString); return(json); } return(null); }
public static string GetPostString(string url, string data, ContentType contentType = ContentType.application_json) { try { byte[] postBytes = System.Text.Encoding.GetEncoding("utf-8").GetBytes(data); System.Net.HttpWebRequest myRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); myRequest.Method = "POST"; myRequest.ContentType = contentType.ToContentTypeStr(); myRequest.ContentLength = postBytes.Length; myRequest.Proxy = null; System.IO.Stream newStream = myRequest.GetRequestStream(); newStream.Write(postBytes, 0, postBytes.Length); newStream.Close(); // Get response System.Net.HttpWebResponse myResponse = (System.Net.HttpWebResponse)myRequest.GetResponse(); using (System.IO.StreamReader reader = new System.IO.StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"))) { string content = reader.ReadToEnd(); return(content); } } catch (System.Exception ex) { return(ex.Message); } }
/// <summary> /// POST获取网址数据 /// </summary> /// <param name="url">请求网址</param> /// <param name="postData">发送内容</param> /// <param name="cert">X509证书文件</param> /// <returns></returns> public static string PostToUrl(string url, string postData, X509Certificate2 cert) { try { System.Net.HttpWebRequest webrequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url); webrequest.ClientCertificates.Add(cert); byte[] bs = Encoding.UTF8.GetBytes(postData); webrequest.Method = "POST"; webrequest.ContentType = "application/x-www-form-urlencoded"; webrequest.ContentLength = bs.Length; using (Stream reqStream = webrequest.GetRequestStream()) { reqStream.Write(bs, 0, bs.Length); reqStream.Close(); } System.Net.HttpWebResponse webreponse = (System.Net.HttpWebResponse)webrequest.GetResponse(); Stream stream = webreponse.GetResponseStream(); string resp = string.Empty; using (StreamReader reader = new StreamReader(stream)) { resp = reader.ReadToEnd(); } return(resp); } catch (Exception ex) { throw new Exception(ex.Message); } }
public static string GetAPIResponse(string url, byte[] bytefile) { string response = String.Empty; try { //Call to get AccessToken string accessToken = GetSharePointAccessToken(); //Call to get the REST API response from Sharepoint System.Net.HttpWebRequest endpointRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url); endpointRequest.Method = "POST"; endpointRequest.Headers.Add("binaryStringRequestBody", "true"); endpointRequest.GetRequestStream().Write(bytefile, 0, bytefile.Length); //endpointRequest.Accept = "application/json;odata=verbose"; endpointRequest.Timeout = 1000000; endpointRequest.Headers.Add("Authorization", "Bearer " + accessToken); System.Net.WebResponse webResponse = endpointRequest.GetResponse(); Stream webStream = webResponse.GetResponseStream(); StreamReader responseReader = new StreamReader(webStream); response = responseReader.ReadToEnd(); return(response); } catch (Exception ex) { throw; } }
private void UploadFileOnStorage(CloudAppConfig Config, MemoryStream fileStream) { string URIRequest = Config.ProductUri + "/storage/file/" + Config.FileName; string URISigned = Sign(URIRequest, Config.AppSID, Config.AppKey); try { System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(URISigned); req.Method = "PUT"; req.ContentType = "application/x-www-form-urlencoded"; req.AllowWriteStreamBuffering = true; using (System.IO.Stream reqStream = req.GetRequestStream()) { reqStream.Write(fileStream.ToArray(), 0, (int)fileStream.Length); } string statusCode = null; using (System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)req.GetResponse()) { statusCode = response.StatusCode.ToString(); } } catch (System.Net.WebException webex) { throw new Exception(webex.Message); } catch (Exception ex) { throw new Exception(ex.Message); } }
//title–消息标题, //content – 消息内容 //type – 消息类型,1:消息 2:通知 //platform - 0:全部平台,1:ios, 2:android //groupName - 推送组名,多个组用英文逗号隔开.默认:全部组。eg.group1,group2 . //userIds - 推送用户id, 多个用户用英文逗号分隔,eg. user1,user2。 public void ts_01() { string formData = String.Format("title={0}&content={1}&type={2}&platform={3}&groupName={4}&userIds={5}", title, content, type, 0, groupName, userIds); //标题1 内容2 消息1/通知2 平台0全部1ios2案桌 制定用户5 (还可以制定群组) string url = String.Format("https://p.apicloud.com/api/push/message"); System.Net.HttpWebRequest request = System.Net.HttpWebRequest.Create(url) as System.Net.HttpWebRequest; request.Method = "POST"; request.Headers.Add("X-APICloud-AppId", AppID); request.Headers.Add("X-APICloud-AppKey", GetSHA1Key(AppID, AppKey)); //aha1加密 request.ContentType = "application/x-www-form-urlencoded"; byte[] postData = System.Text.Encoding.UTF8.GetBytes(formData); request.ContentLength = postData.Length; using (System.IO.Stream reqStream = request.GetRequestStream()) { //StreamWriter reqWriter = new StreamWriter(reqStream); reqStream.Write(postData, 0, postData.Length); //reqWriter.Write(formData); using (var response = request.GetResponse() as System.Net.HttpWebResponse) { using (System.IO.Stream respSream = response.GetResponseStream()) { System.IO.StreamReader respReader = new System.IO.StreamReader(respSream); string result = respReader.ReadToEnd(); //Console.WriteLine(result); } } } }
/// <summary> /// Updates our directory server with blo info /// </summary> private void sendDataToDirectory() { System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://infdir1.aaerox.com/directory"); byte[] bytes = Encoding.UTF8.GetBytes(string.Format("{0}/{1}", Environment.CurrentDirectory, _bloListFileName)); webRequest.Method = "PUT"; webRequest.ContentType = "application/json"; webRequest.ContentLength = bytes.Length; try { webRequest.GetRequestStream().Write(bytes, 0, bytes.Length); } catch (Exception e) { Log.write(TLog.Exception, string.Format("Data To Directory Server: {0}", e.ToString())); } try { using (System.IO.StreamReader reader = new System.IO.StreamReader(webRequest.GetResponse().GetResponseStream())) { reader.ReadToEnd(); reader.Close(); } } catch (Exception e) { Log.write(TLog.Exception, string.Format("Data To Directory Server: {0}", e.ToString())); } }
//public void GetConfigINIFile() //{ // INIFile INIFile = new INIFile(); // INIFile.INIPath = System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini"; // OraStr = INIFile.GetStrFromINI("Server", "OraStr", ""); // ServerAddress = INIFile.GetStrFromINI("Server", "ServerAddress", ""); // CookieTimeOut = Val(INIFile.GetStrFromINI("Server", "CookieTimeOut", "")); // EMSImagePath = INIFile.GetStrFromINI("Server", "EMSImagePath", ""); // EMSImagePath = Replace((EMSImagePath + "\\"), "\\\\", "\\"); //} public string PostHttpResponse(string StrUrl, string PostData) { try { System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(StrUrl); req.Credentials = System.Net.CredentialCache.DefaultCredentials; req.Timeout = 8000; //8秒超时的设置 req.Method = "POST"; byte[] byte1 = System.Text.Encoding.Default.GetBytes(PostData); req.ContentLength = byte1.Length; req.ContentType = "application/x-www-form-urlencoded"; System.IO.Stream requestStream = req.GetRequestStream(); requestStream.Write(byte1, 0, byte1.Length); requestStream.Close(); //get sp 输出并分析成功还是失败 System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)req.GetResponse(); System.IO.StreamReader sr = new System.IO.StreamReader(res.GetResponseStream(), System.Text.Encoding.Default); return(sr.ReadToEnd()); } catch (Exception ex) { return("->调度请求超时"); } }
public string HttpPost(string URI, string Parameters) { System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(URI); //req.Proxy = new System.Net.WebProxy(ProxyString, true); req.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; req.Headers.Add("Accept-Encoding:gzip, deflate"); req.Headers.Add("Accept-Language:utf-8"); req.Headers.Add("UA-CPU:x86"); req.Headers.Add(System.Net.HttpRequestHeader.CacheControl, "no-cache"); req.AllowAutoRedirect = true; req.ContentType = "application/x-www-form-urlencoded"; req.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-silverlight, */*"; req.Method = "POST"; req.ServicePoint.Expect100Continue = false; byte[] bytes = System.Text.Encoding.UTF8.GetBytes(Parameters); req.ContentLength = bytes.Length; System.IO.Stream os = req.GetRequestStream(); os.Write(bytes, 0, bytes.Length); os.Close(); System.Net.WebResponse resp = req.GetResponse(); if (resp == null) { return(null); } System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()); return(sr.ReadToEnd().Trim()); }
public void webRequest() { System.Net.ServicePointManager.Expect100Continue = false; RequestEvent requestEvent = new RequestEvent(); string message = requestEvent.createOadrRequestEvent("TH_VEN"); System.Net.HttpWebRequest wr = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(m_url + "/EiEvent"); wr.Method = "POST"; System.Net.NetworkCredential nc = new System.Net.NetworkCredential("admin", "password"); wr.ContentType = "application/xml"; Stream s = wr.GetRequestStream(); s.Write(Encoding.UTF8.GetBytes(message), 0, message.Length); wr.Credentials = nc.GetCredential(wr.RequestUri, "Basic"); System.Net.WebResponse response = wr.GetResponse(); Stream stream = response.GetResponseStream(); StreamReader streamReader = new StreamReader(stream); string responseBody = streamReader.ReadToEnd(); System.Console.WriteLine(responseBody); }
public static string GetWanIP(string url) { //http://www.ip138.com/ip2city.asp Uri uri = new Uri(url); System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = 0; req.CookieContainer = new System.Net.CookieContainer(); req.GetRequestStream().Write(new byte[0], 0, 0); System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)(req.GetResponse()); StreamReader rs = new StreamReader(res.GetResponseStream(), System.Text.Encoding.GetEncoding("GB18030")); string s = rs.ReadToEnd(); rs.Close(); req.Abort(); res.Close(); //s = "116.10.175.142"; System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(s, @"(\d+)\.(\d+)\.(\d+)\.(\d+)"); if (m.Success) { return(m.Value); } return(string.Empty); }
public object Pay(PosForm pf, ref string provNumber, ref string provMessage, IHttpContextAccessor accessor = null) { string expMonth = string.Format("{0:00}", Convert.ToInt32(pf.Month)); string expYear = string.Format("{0:00}", Convert.ToInt32(pf.Year.ToString().Substring(2, 2))); String responseStr = ""; String format = "{0}={1}&"; StringBuilder sb = new StringBuilder(); sb.AppendFormat(format, "ShopCode", "2927"); sb.AppendFormat(format, "PurchAmount", Convert.ToDecimal(pf.Price)); sb.AppendFormat(format, "Currency", "949"); string provizyonalOrderId = Guid.NewGuid().ToString(); sb.AppendFormat(format, "OrderId", provizyonalOrderId);//orderId); sb.AppendFormat(format, "InstallmentCount", pf.Installments); sb.AppendFormat(format, "txnType", "Auth"); sb.AppendFormat(format, "orgOrderId", ""); sb.AppendFormat(format, "UserCode", "sedamakapi"); // api için olanı yazdık sb.AppendFormat(format, "UserPass", "tE3mx"); sb.AppendFormat(format, "SecureType", "NonSecure"); sb.AppendFormat(format, "Pan", pf.CardNumber.ToString()); sb.AppendFormat(format, "Expiry", expMonth + expYear); sb.AppendFormat(format, "Cvv2", pf.SecureCode.ToString()); sb.AppendFormat(format, "BonusAmount", 0); sb.AppendFormat(format, "CardType", pf.CardNumber.ToString().StartsWith("4") ? 0 : 1); sb.AppendFormat(format, "Lang", "TR"); sb.AppendFormat(format, "MOTO", "1"); //sb.AppendFormat(format, "Description", "yeni işlem"); //Request.Form["Description"] //Eğer 3D doğrulaması yapılmış ise aşağıdaki alanlar da gönderilmelidir*/ /* //sb.AppendFormat(format, "PayerAuthenticationCode", Request.Form["PayerAuthenticationCode"]); //sb.AppendFormat(format, "Eci", Request.Form["Eci"]);//Visa - 05,06 MasterCard 01,02 olabilir //sb.AppendFormat(format, "PayerTxnId", Request.Form["PayerTxnId"]); try { System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://spos.denizbank.com/mpi/Default.aspx"); byte[] parameters = System.Text.Encoding.GetEncoding("ISO-8859-9").GetBytes(sb.ToString()); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = parameters.Length; System.IO.Stream requeststream = request.GetRequestStream(); requeststream.Write(parameters, 0, parameters.Length); requeststream.Close(); //Response.Write(sb.ToString()); System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)request.GetResponse(); System.IO.StreamReader responsereader = new System.IO.StreamReader(resp.GetResponseStream(), System.Text.Encoding.GetEncoding("ISO-8859-9")); responseStr = responsereader.ReadToEnd(); } catch (Exception ex) { return(ErrorMessage = "ErrorMessage=" + ex.Message); } return(responseStr); }
private string sendRequest(string req_xml, System.ComponentModel.BackgroundWorker bw) { int counter = 0; string ret = "Unknown Error"; XmlDocument soap_env = new XmlDocument(); soap_env.LoadXml(req_xml); request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); request.Headers.Add("SOAPAction", soap_action); request.ContentType = "text/xml;charset=\"utf-8\""; request.Method = "POST"; request.CookieContainer = cookie; request.KeepAlive = false; //true request.UserAgent = "Small Craft C#"; // Ignore SSL Error if using https System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate( Object obj, X509Certificate certificate, X509Chain chain, System.Net.Security.SslPolicyErrors errors) { return (true); }; Stream stream = request.GetRequestStream(); soap_env.Save(stream); try { string buf = ""; System.Net.WebResponse response = request.GetResponse(); Stream s = response.GetResponseStream(); StreamReader sr = new StreamReader(s); while (!sr.EndOfStream) { buf += sr.ReadLine(); counter++; if (reportProgress) { bw.ReportProgress(counter); } } ret = buf; } catch (System.Net.WebException webExc) { ret = webExc.ToString(); } return ret; }
private String PerformRequest(String method, String url, String data) { if ((method.CompareTo("GET") == 0) && (!String.IsNullOrEmpty(data))) { if (url.Contains("?")) { url = url + "&"; } else { url = url + "?"; } url = url + data; } //Create connection connection = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); connection.UserAgent = "Veridu-CSharp/" + sdkVersion; connection.Headers.Add("Veridu-Client", this.clientId); if (!String.IsNullOrEmpty(this.sessionToken)) { connection.Headers.Add("Veridu-Session", this.sessionToken); } connection.Method = method; connection.Timeout = 10000; connection.ReadWriteTimeout = 10000; connection.ContentType = "application/x-www-form-urlencoded"; //Send request if (!String.IsNullOrWhiteSpace(data) && !method.Contains("GET")) { UTF8Encoding encoding = new UTF8Encoding(); byte[] bytes = encoding.GetBytes(data); connection.ContentLength = bytes.Length; using (System.IO.Stream dataStream = connection.GetRequestStream()) { dataStream.Write(bytes, 0, bytes.Length); } } else { connection.ContentLength = 0; } //Get Response string result = ""; try { using (System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)connection.GetResponse()) { System.Net.HttpStatusCode status = response.StatusCode; System.IO.Stream receiveStream = response.GetResponseStream(); System.IO.StreamReader sr = new System.IO.StreamReader(receiveStream); result = sr.ReadToEnd().Trim(); } } catch (Exception ex) { System.Net.WebException wex = (System.Net.WebException)ex; var s = wex.Response.GetResponseStream(); result = ""; int lastNum = 0; do { lastNum = s.ReadByte(); result += (char)lastNum; } while (lastNum != -1); s.Close(); s = null; } return result; }