GetRequestStream() public method

public GetRequestStream ( ) : System.IO.Stream
return System.IO.Stream
コード例 #1
0
ファイル: EasyWebRequest.cs プロジェクト: jpesquibel/Projects
            public EasyWebRequest(string method, string userName, string password, string authID, string masterKey, string baseURL, string contraint)
            {
                request = WebRequest.Create(baseURL);
                request.ContentType = "text/xml";
                request.Credentials = new NetworkCredential(userName, password);
                request.Headers.Add("X-Parse-Application-Id: " + authID);
                request.Headers.Add("X-Parse-Master-Key: " + masterKey);

                if (method.Equals("GET") || method.Equals("POST"))
                    request.Method = method;
                else
                    throw new Exception("Invalid Method Type");

                string postData = contraint;
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);

                request.ContentType = "application/x-www-form-urlencoded";

                request.ContentLength = byteArray.Length;

                dataStream = request.GetRequestStream();

                dataStream.Write(byteArray, 0, byteArray.Length);

                dataStream.Close();
 
            }
コード例 #2
0
        public void CreateMultipartRequest(WebRequest request)
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", CultureInfo.InvariantCulture);
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.ContentLength = CalculateContentLength(boundary);

            using (Stream stream = request.GetRequestStream())
            {
                foreach (var item in _formData)
                {
                    string header = String.Format(CultureInfo.InvariantCulture, FormDataTemplate, boundary, item.Key, item.Value);
                    byte[] headerBytes = Encoding.UTF8.GetBytes(header);
                    stream.Write(headerBytes, 0, headerBytes.Length);
                }

                byte[] newlineBytes = Encoding.UTF8.GetBytes(Environment.NewLine);
                foreach (var file in _files)
                {
                    string header = String.Format(CultureInfo.InvariantCulture, FileTemplate, boundary, file.FieldName, file.FieldName, file.ContentType);
                    byte[] headerBytes = Encoding.UTF8.GetBytes(header);
                    stream.Write(headerBytes, 0, headerBytes.Length);

                    Stream fileStream = file.FileFactory();
                    fileStream.CopyTo(stream, bufferSize: 4 * 1024);
                    fileStream.Close();
                    stream.Write(newlineBytes, 0, newlineBytes.Length);
                }

                string trailer = String.Format(CultureInfo.InvariantCulture, "--{0}--", boundary);
                byte[] trailerBytes = Encoding.UTF8.GetBytes(trailer);
                stream.Write(trailerBytes, 0, trailerBytes.Length);
            }
        }
コード例 #3
0
ファイル: TestUtils.cs プロジェクト: turbonaitis/stubby4net
 public static void WritePost(WebRequest request, string post)
 {
     using(var stream = request.GetRequestStream())
     using(var writer = new StreamWriter(stream)) {
         writer.Write(post);
     }
 }
コード例 #4
0
 private static void SetRequestBody(WebRequest webRequest, string body)
 {
     byte[] buffer = Encoding.UTF8.GetBytes(body);
     webRequest.ContentLength = buffer.Length;
     using (Stream requestStream = webRequest.GetRequestStream())
         requestStream.Write(buffer, 0, buffer.Length);
 }
コード例 #5
0
        public static string SendHttpPost(WebRequest request, YahooMessengerAuthentication authentication, string content)
        {
            request.Method = "POST";
            byte[] byteArray = Encoding.UTF8.GetBytes(content);
            request.ContentLength = byteArray.Length;
            var dataStream = request.GetRequestStream();
            // Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length);
            // Close the Stream object.
            dataStream.Close();
            using(var response = (HttpWebResponse) request.GetResponse())
            {
                if (response == null) throw new NullReferenceException();

                var respCode = response.StatusCode;

                if (respCode != HttpStatusCode.OK)
                    throw new HttpException(HttpException.HTTP_OK_NOT_RECEIVED, respCode.ToString());

                dataStream = response.GetResponseStream();
                if (dataStream == null) throw new NullReferenceException();
                var reader = new StreamReader(dataStream);

                var responseFromServer = new StringBuilder("");
                responseFromServer.Append(reader.ReadToEnd());
                reader.Close();
                dataStream.Close();
                response.Close();

                return responseFromServer.ToString();
            }
        }
コード例 #6
0
ファイル: AsyncWebRequest.cs プロジェクト: ReizeiMako/Oxide
        private void Worker()
        {
            try
            {
                //Main.Log("Creating request...");
                request = WebRequest.Create(url);
                request.Credentials = CredentialCache.DefaultCredentials;
                //30 Second timeout instead of 2 minutes before.
                request.Timeout = 30000;
                //Main.Log("Waiting for response...");

                if (this.ispost == true && this.postdata != null)
                {
                    request.Method = "POST";
                    byte[] bytePostData = Encoding.UTF8.GetBytes(postdata);

                    request.ContentType = "application/x-www-form-urlencoded";
                    request.ContentLength = bytePostData.Length;

                    Stream postStream = request.GetRequestStream();
                    postStream.Write(bytePostData, 0, bytePostData.Length);
                    postStream.Close();
                }

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                if (response == null)
                {
                    // Uhh panic what do we do
                    Logger.Error("AsyncWebRequest panic: Response is null!");
                    return;
                }
                //Main.Log("Reading response stream...");
                Stream strm = response.GetResponseStream();
                StreamReader rdr = new StreamReader(strm);
                Response = rdr.ReadToEnd();
                ResponseCode = (int)response.StatusCode;
                rdr.Close();
                strm.Close();
                response.Close();
                //Main.Log("Web request complete.");
            }
            catch (WebException webex)
            {
                var response = webex.Response as HttpWebResponse;
                Response = webex.Message;
                ResponseCode = (int)response.StatusCode;
            }
            catch (Exception ex)
            {
                Response = ex.ToString();
                ResponseCode = -1;
                Logger.Error(ex.ToString());
            }
            finally
            {
                Complete = true;
            }
            
        }
コード例 #7
0
        public static Stream GetRequestStream(WebRequest request)
        {
#if WINDOWS_PHONE            
            return WebRequestStreamHelper.GetRequestStreamInternal(request);
#else
            return request.GetRequestStream();
#endif
        }
コード例 #8
0
ファイル: WebRequestBuilder.cs プロジェクト: ijoyce/Fetch
 private void SetRequestBody(WebRequest request, string body)
 {
     var byteArray = Encoding.UTF8.GetBytes(body);
     request.ContentLength = byteArray.Length;
     var dataStream = request.GetRequestStream();
     dataStream.Write(byteArray, 0, byteArray.Length);
     dataStream.Close();
 }
コード例 #9
0
 public static void WriteStringToRequestStream(WebRequest request, string data)
 {
     using (var streamWriter = new StreamWriter(request.GetRequestStream()))
     {
         streamWriter.Write(data);
         streamWriter.Flush();
     }
 }
コード例 #10
0
ファイル: CoursioApi.cs プロジェクト: punarinta/coursio-api
        public void Auth()
        {
            // setup connection to endpoint
            request = WebRequest.Create(baseUrl + "auth");

            // compute HMAC
            var enc = Encoding.ASCII;
            HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(privateKey));
            hmac.Initialize();

            var timestamp = DateTime.Now.ToString(@"MM\/dd\/yyyy hh\:mm");
            byte[] buffer = enc.GetBytes(publicKey + timestamp + salt);
            var hash = BitConverter.ToString(hmac.ComputeHash(buffer)).Replace("-", "").ToLower();

            request.Headers ["X-Coursio-apikey"] = publicKey;
            request.Headers ["X-Coursio-time"] = timestamp;
            request.Headers ["X-Coursio-random"] = salt;
            request.Headers ["X-Coursio-hmac"] = hash;
            request.Method = "POST";

            byte[] byteArray = Encoding.UTF8.GetBytes ("{\"method\":\"loginHmac\"}");

            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;

            // Write data to the Stream
            Stream dataStream = request.GetRequestStream ();
            dataStream.Write (byteArray, 0, byteArray.Length);
            dataStream.Close ();

            // Get the response.
            WebResponse response = request.GetResponse ();

            // Get the stream content and read it
            Stream dataStream2 = response.GetResponseStream ();
            StreamReader reader = new StreamReader (dataStream2);

            // Read the content.
            string responseFromServer = reader.ReadToEnd ();

            // Clean up
            reader.Close ();
            dataStream2.Close ();
            response.Close ();

            Regex regex = new Regex(@"""sessionId"":""(.*?)""");
            Match match = regex.Match(responseFromServer);
            if (match.Success)
            {
                sessionId = match.Groups[1].Value;
            }
            else
            {
                throw new System.Exception ("Login failed");
            }
        }
コード例 #11
0
        public override void WriteStreamRequestToTarget(HttpContextBase context, WebRequest request)
        {
            var serviceBusContext = (AzureServiceBusHttpContext)context;
            var requestContext = serviceBusContext.RequestContext;

            using (var requestStream = request.GetRequestStream())
            {
                _webEncoder.WriteMessage(requestContext.RequestMessage, requestStream);
            }
        }
コード例 #12
0
ファイル: SshCommand.cs プロジェクト: 0be1/opensshsync
        public SshCommand(WebRequest request)
        {
            this.request = request;

            this.headers = new WebHeaderCollection ();

            process = Process.Start (new ProcessStartInfo {
                FileName = OpenSSHSyncExt.SSH,
                Arguments = "-q -o 'BatchMode=yes' -o 'PasswordAuthentication=no' " + GetSession (request) + " " + GetCommand (request),
                UseShellExecute = false,
                CreateNoWindow = true,
                RedirectStandardInput = true,
                RedirectStandardOutput = true
            });

            if (request.GetRequestStream () != null) {
                request.GetRequestStream ().CopyTo (process.StandardInput.BaseStream);
            }
        }
コード例 #13
0
 private static void AddPostData(WebRequest webRequest, string data)
 {
     webRequest.Method = "POST";
     var bytes = Encoding.UTF8.GetBytes(data);
     webRequest.ContentLength = bytes.Length;
     webRequest.ContentType = "application/x-www-form-urlencoded";
     using (var requestStream = webRequest.GetRequestStream())
     {
         requestStream.Write(bytes, 0, bytes.Length);
     }
 }
コード例 #14
0
        /// <summary>
        ///     Method for adding a request body for put and post
        ///     http calls.
        /// </summary>
        /// <param name="webRequest"></param>
        /// <param name="request"></param>
        private void AddRequestBody(ref WebRequest webRequest, HttpRequest request)
        {
            byte[] byteArray = Encoding.UTF8.GetBytes(request.Body);
            webRequest.ContentType = request.ContentType ?? "text/xml; charset=UTF-8";
            webRequest.ContentLength = byteArray.Length;

            using (Stream requestBody = webRequest.GetRequestStream())
            {
                requestBody.Write(byteArray, 0, byteArray.Length);
                requestBody.Close();
            }
        }
コード例 #15
0
 private void connectionInit(CaptchaTraderRequestType type, String username, String password)
 {
     string param = (type.doPost || username == null || password == null) ? "" : "/username:"******"/password:"******".xml");
     _urlConnection = WebRequest.Create(_url);
     _urlConnection.Method = (type.doPost ? "POST" : "GET");
     if (type.doPost)
     {
         _urlConnection.ContentType = "multipart/form-data; boundary=" + _boundary;
         _os = _urlConnection.GetRequestStream();
     }
 }
コード例 #16
0
        public override System.Net.WebRequest MakeRequest()
        {
            System.Net.WebRequest req = System.Net.WebRequest.Create("/xkAction.do");
            req.Method        = HttpMethod;
            req.ContentType   = "application/x-www-form-urlencoded";
            req.ContentLength = ContentLength;
            StreamWriter sw = new StreamWriter(req.GetRequestStream());

            sw.Write("kcId=" + CourseSerial + "_" + SequenceNo + "&preActionType=5&actionType=9");
            sw.Close();
            return(req);
        }
コード例 #17
0
 private static string GetHttpWebResponse(WebRequest httpWebRequest, string postData)
 {
     var requestWriter = new StreamWriter(httpWebRequest.GetRequestStream());
     try
     {
         requestWriter.Write(postData);
     }
     finally
     {
         requestWriter.Close();
     }
     return GetHttpWebResponse(httpWebRequest);
 }
コード例 #18
0
ファイル: HttpPost.cs プロジェクト: cvs1989/hooyeswidget
 private static string GetHttpWebResponse(WebRequest httpWebRequest, byte[] bytes)
 {
     var requestStream = httpWebRequest.GetRequestStream();
     try
     {
         requestStream.Write(bytes, 0, bytes.Length);
     }
     finally
     {
         requestStream.Close();
     }
     return GetHttpWebResponse(httpWebRequest);
 }
コード例 #19
0
        public override System.Net.WebRequest MakeRequest()
        {
            System.Net.WebRequest req = System.Net.WebRequest.Create("/loginAction.do");
            req.Method        = HttpMethod;
            req.ContentType   = "application/x-www-form-urlencoded";
            req.ContentLength = ContentLength;

            StreamWriter sw = new StreamWriter(req.GetRequestStream());

            sw.Write("zjh=" + UserName + "&mm=" + Password);
            sw.Close();
            return(req);
        }
コード例 #20
0
ファイル: NeteaseMessage.cs プロジェクト: radtek/cccc
    //发送验证码
    public string SendCode(string mobile, string deviceId)
    {
        int templateid = 0;
        int codeLen    = 6;
        //生成6位随机数
        string nonce = new Random().Next(100000, 999999).ToString();
        //系统当前的UTC时间戳
        string curTime = DateTimeToStamp(DateTime.Now).ToString();

        //三个参数拼接的字符串进行sha1哈希计算的草的16进制字符串,有效期为5分钟
        string checkSum = getCheckSum(appSecret, nonce, curTime);

        //拼接发送消息的头部
        string post = "mobile=" + mobile + "&templateid=" + templateid;

        if (!string.IsNullOrEmpty(deviceId))
        {
            post += "&deviceId=" + deviceId;
        }

        post = post + "&codeLen=" + codeLen;


        byte[] btBodys = Encoding.UTF8.GetBytes(post);

        System.Net.WebRequest wReq = System.Net.WebRequest.Create(url);
        wReq.Method = "POST";
        wReq.Headers.Add("AppKey", appKey);
        wReq.Headers.Add("Nonce", nonce);
        wReq.Headers.Add("CurTime", curTime);
        wReq.Headers.Add("CheckSum", checkSum);
        wReq.ContentLength = btBodys.Length;
        wReq.ContentType   = "application/x-www-form-urlencoded;charset=utf-8";

        using (var wsr = wReq.GetRequestStream())
        {
            wsr.Write(btBodys, 0, btBodys.Length);
        }

        System.Net.WebResponse wResp      = wReq.GetResponse();
        System.IO.Stream       respStream = wResp.GetResponseStream();

        string result;

        using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, System.Text.Encoding.UTF8))
        {
            result = reader.ReadToEnd();
        }
        //Json数据,obj是网易生成的验证码
        return(result);
    }
コード例 #21
0
        public static bool GetAccesToken(string strDemo, out string strMessage)
        {
            bool blnResult = false;

            try
            {
                string strClientSecretID = cSettings[0].ClientID + ":" + cSettings[0].ClientSecret;
                strMessage = "";
                string strUrl = "";

                if (strDemo == "SandBox")
                {
                    strUrl = cSettings[0].UrlSandBoxToken;
                }
                else
                {
                    strUrl = cSettings[0].UrlApiToken;
                }

                System.Net.WebRequest request = System.Net.HttpWebRequest.Create(strUrl);
                request.Method      = "POST";
                request.ContentType = "application/json; charset=UTF-8";

                CredentialCache mycache = new CredentialCache();
                mycache.Add(new Uri(strUrl), "Basic", new NetworkCredential(cSettings[0].ClientID, cSettings[0].ClientSecret));
                request.Credentials = mycache;
                request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(strClientSecretID)));

                Stream postStream = request.GetRequestStream();
                postStream.Flush();
                postStream.Close();

                using (System.Net.WebResponse response = request.GetResponse())
                {
                    using (System.IO.StreamReader streamReader = new System.IO.StreamReader(response.GetResponseStream()))
                    {
                        dynamic jsonResponseText          = streamReader.ReadToEnd();
                        RefreshTokenResultJSON jsonResult = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(jsonResponseText, typeof(RefreshTokenResultJSON));
                        cSettings[0]._AccesToken = jsonResult.access_token;
                    }
                }
                blnResult = true;
            }
            catch (Exception ex)
            {
                strMessage = ex.Message.ToString();
                blnResult  = false;
            }

            return(blnResult);
        }
コード例 #22
0
 // Sends request to DataManagementSystem
 private static Boolean handleRequest(WebRequest request, byte[] byteArray)
 {
     try
     {
         Stream dataStream = request.GetRequestStream();
         dataStream.Write(byteArray, 0, byteArray.Length);
         dataStream.Close();
         return true;
     }
     catch
     {
         return false;
     }
 }
コード例 #23
0
        private void technetSample()
        {
            string    URLAuth   = "https://technet.rapaport.com/HTTP/Authenticate.aspx";
            WebClient webClient = new WebClient();

            NameValueCollection formData = new NameValueCollection();

            formData["Username"] = "******";
            formData["Password"] = "******";

            byte[] responseBytes    = webClient.UploadValues(URLAuth, "POST", formData);
            string resultAuthTicket = Encoding.UTF8.GetString(responseBytes);

            webClient.Dispose();

            string URL      = "http://technet.rapaport.com/HTTP/Upload/Upload.aspx?Method=file";
            string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");

            System.Net.WebRequest webRequest = System.Net.WebRequest.Create(URL);

            webRequest.Method      = "POST";
            webRequest.ContentType = "multipart/form-data; boundary=" + boundary;

            string FilePath = "C:\\test.csv";

            formData.Clear();
            formData["ticket"]     = resultAuthTicket;
            formData["ReplaceAll"] = "false";

            Stream postDataStream = GetPostStream(FilePath, formData, boundary);

            webRequest.ContentLength = postDataStream.Length;
            Stream reqStream = webRequest.GetRequestStream();

            postDataStream.Position = 0;

            byte[] buffer    = new byte[1024];
            int    bytesRead = 0;

            while ((bytesRead = postDataStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                reqStream.Write(buffer, 0, bytesRead);
            }

            postDataStream.Close();
            reqStream.Close();

            StreamReader sr     = new StreamReader(webRequest.GetResponse().GetResponseStream());
            string       Result = sr.ReadToEnd();
        }
コード例 #24
0
        public void MessageUpdate(int stroka, string str)
        {
            System.Net.WebRequest req = System.Net.WebRequest.Create("http://localhost:38126/api/values/" + stroka.ToString());
            req.Method      = "PUT";
            req.Timeout     = 50000;
            req.ContentType = "application/x-www-form-urlencoded";
            byte[] sentData = Encoding.GetEncoding(1251).GetBytes(str);
            req.ContentLength = sentData.Length;
            System.IO.Stream sendStream = req.GetRequestStream();
            sendStream.Write(sentData, 0, sentData.Length);
            sendStream.Close();

            System.Net.WebResponse res = req.GetResponse();
        }
コード例 #25
0
        public CorreiosMobileCrawler(int zipCode)
        {
            _zipCode = zipCode;
            _request = WebRequest.Create(ConfigurationManager.AppSettings["UriCorreios"]);
            _request.ContentType = "application/x-www-form-urlencoded";
            _request.Headers.Set(HttpRequestHeader.ContentEncoding, "ISO-8859-1");
            _request.Method = "POST";
            var requestParams = Encoding.ASCII.GetBytes(string.Format("cepEntrada={0}&tipoCep=&cepTemp&metodo=buscarCep", zipCode));
            _request.ContentLength = requestParams.Length;

            var requestStream = _request.GetRequestStream();
            requestStream.Write(requestParams, 0, requestParams.Length);
            requestStream.Close();
        }
コード例 #26
0
        private static string PostDataToURL(string szUrl, string szData)
        {     //Setup the web request
            string szResult = string.Empty;

            System.Net.WebRequest Request = WebRequest.Create(szUrl);
            Request.Timeout     = 30000;
            Request.Method      = "POST";
            Request.ContentType = "application/x-www-form-urlencoded";

            //Set the POST data in a buffer
            byte[] PostBuffer;
            try

            { // replacing " " with "+" according to Http post RPC
                szData = szData.Replace(" ", "+");

                //Specify the length of the buffer
                PostBuffer            = Encoding.UTF8.GetBytes(szData);
                Request.ContentLength = PostBuffer.Length;

                //Open up a request stream
                Stream RequestStream = Request.GetRequestStream();

                //Write the POST data
                RequestStream.Write(PostBuffer, 0, PostBuffer.Length);

                //Close the stream
                RequestStream.Close();
                //Create the Response object
                WebResponse Response;
                Response = Request.GetResponse();

                //Create the reader for the response
                StreamReader sr = new StreamReader(Response.GetResponseStream(), Encoding.UTF8);

                //Read the response
                szResult = sr.ReadToEnd();

                //Close the reader, and response
                sr.Close();
                Response.Close();

                return(szResult);
            }
            catch (Exception e)
            {
                return(szResult);
            }
        }
コード例 #27
0
        /// <summary>
        /// This is Preview Code.
        /// Create Power BI Group using, graph API.
        /// This code will be changed shortly when the new PowerBI REST API for group creation is implemented
        /// </summary>
        /// <param name="groupName"></param>
        /// <returns></returns>
        public static async Task <O365Group> CreateGroup(string groupName)
        {
            var newGroup = new O365Group
            {
                DisplayName     = groupName,
                Description     = "Autogenerated by Migration Sample",
                MailNickname    = groupName,
                MailEnabled     = true,
                Visibility      = "Private",
                SecurityEnabled = false,
                GroupTypes      = new List <string> {
                    "Unified"
                }
            };

            System.Net.WebRequest request = System.Net.WebRequest.Create(
                String.Format("{0}/groups",
                              GraphUrlWithVersion)) as System.Net.HttpWebRequest;

            request.Method = "POST";
            request.Headers.Add("Authorization", String.Format("Bearer {0}", AzureTokenManager.GetGraphToken()));
            request.ContentType = "application/json";
            byte[] postBytes     = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(newGroup));
            Stream requestStream = request.GetRequestStream();

            requestStream.Write(postBytes, 0, postBytes.Length);
            requestStream.Close();

            O365Group createdGroup = new O365Group();

            using (var response = await request.GetResponseAsync() as System.Net.HttpWebResponse)
            {
                //Get reader from response stream
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    //Deserialize JSON string
                    createdGroup = JsonConvert.DeserializeObject <O365Group>(reader.ReadToEnd());
                }
            }

            if (!await AddToGroup(createdGroup.Id, AzureTokenManager.GetGraphToken(), AzureTokenManager.GetGraphUserUniqueId()))
            {
                await DeleteGroup(createdGroup.Id);

                return(null);
            }

            return(createdGroup);
        }
コード例 #28
0
        private void submitDebug()
        {
            string info = ("Submitted issue: " + Environment.NewLine + richTextBox1.Text + Environment.NewLine + Environment.NewLine + "Debug info: " + Environment.NewLine + Environment.NewLine + debug);

            System.Net.WebRequest req = System.Net.WebRequest.Create(IssueHook);
            req.ContentType = "application/x-www-form-urlencoded";
            req.Method      = "POST";
            string content2 = "body=" + info;

            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(content2);
            req.ContentLength = bytes.Length;
            System.IO.Stream os = req.GetRequestStream();
            os.Write(bytes, 0, bytes.Length);
            os.Close();
        }
コード例 #29
0
        static void SendSms(String destinationAccount, String message)
        {
            // Based on code from http://www.hanselman.com/blog/HTTPPOSTsAndHTTPGETsWithWebClientAndCAndFakingAPostBack.aspx
            string jsonRequest = "";

            System.Net.WebRequest req = System.Net.WebRequest.Create(ConfigurationManager.AppSettings["sms_requestUrl"]);
            req.ContentType = "application/json";
            req.Method      = "POST";
            jsonRequest     = "{\"toNumber\":\"" + destinationAccount + "\",\"message\":\"" + message + "\"}";
            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(jsonRequest);
            req.ContentLength = bytes.Length;
            System.IO.Stream os = req.GetRequestStream();
            os.Write(bytes, 0, bytes.Length);
            os.Close();
        }
コード例 #30
0
ファイル: Http.cs プロジェクト: rhencke/AsanaXP
 private static string GetStringResponse( WebRequest request, string json = "" )
 {
     if( !String.IsNullOrWhiteSpace( json ) )
     {
         using( var sw = new StreamWriter( request.GetRequestStream() ) )
         {
             sw.Write( json );
         }
     }
     using( var response = request.GetResponse() as HttpWebResponse )
     using( var sr = new StreamReader( response.GetResponseStream() ) )
     {
         return sr.ReadToEnd();
     }
 }
コード例 #31
0
        public static void WriteRequest(WebRequest webrequest, string postData)
        {
            webrequest.Method = WebRequestMethods.Http.Post;
            webrequest.ContentType = "application/x-www-form-urlencoded";

            byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);

            webrequest.ContentLength = postDataBytes.Length;

            using (var requestStream = webrequest.GetRequestStream())
            {
                requestStream.Write(postDataBytes, 0, postDataBytes.Length);
                requestStream.Close();
            }
        }
コード例 #32
0
        public string PostMultipartContent(string URL, NameValueCollection formData, string FilePath = null, string basicAuthId = null, string basicAuthPW = null)
        {
            //string URLAuth = "https://technet.rapaport.com/HTTP/Authenticate.aspx";
            //WebClient webClient = new WebClient();
            //NameValueCollection authData = new NameValueCollection();
            //authData["Username"] = "******";
            //authData["Password"] = "******";

            //byte[] responseBytes = webClient.UploadValues(URLAuth, "POST", authData);
            //string resultAuthTicket = Encoding.UTF8.GetString(responseBytes);
            //webClient.Dispose();

            string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");

            System.Net.WebRequest webRequest = System.Net.WebRequest.Create(URL);

            webRequest.Method      = "POST";
            webRequest.ContentType = "multipart/form-data; boundary=" + boundary;

            if (!string.IsNullOrEmpty(basicAuthId) && !string.IsNullOrEmpty(basicAuthPW))
            {
                /* Add Authentication Header Here */
                string authString = basicAuthId + ":" + basicAuthPW;
                webRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(authString));
            }

            Stream postDataStream = GetPostStream(FilePath, formData, boundary);

            webRequest.ContentLength = postDataStream.Length;
            Stream reqStream = webRequest.GetRequestStream();

            postDataStream.Position = 0;

            byte[] buffer    = new byte[1024];
            int    bytesRead = 0;

            while ((bytesRead = postDataStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                reqStream.Write(buffer, 0, bytesRead);
            }

            postDataStream.Close();
            reqStream.Close();

            var response = (HttpWebResponse)webRequest.GetResponse();

            return(new StreamReader(response.GetResponseStream()).ReadToEnd());
        }
コード例 #33
0
ファイル: Android.cs プロジェクト: tranphuong02/meme-app
        private static void GetResponse(WebRequest tRequest, string postData)
        {
            using (var streamWriter = new StreamWriter(tRequest.GetRequestStream()))
            {
                streamWriter.Write(postData);
                streamWriter.Flush();
                streamWriter.Close();

                var httpResponse = (HttpWebResponse)tRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var result = streamReader.ReadToEnd();
                    Debug.WriteLine(result, "Information-SendNotification-Android");
                }
            }
        }
コード例 #34
0
        public static string GetResponse_POST(string url, Dictionary <string, string> parameters)
        {
            try
            {
                //Concatenamos los parametros, OJO: NO se añade el caracter "?"
                string parametrosConcatenados = ConcatParams(parameters);

                System.Net.WebRequest wr = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                wr.Method = "POST";

                wr.ContentType = "application/x-www-form-urlencoded";

                System.IO.Stream newStream;
                //Codificación del mensaje
                System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                byte[] byte1 = encoding.GetBytes(parametrosConcatenados);
                wr.ContentLength = byte1.Length;
                //Envio de parametros
                newStream = wr.GetRequestStream();
                newStream.Write(byte1, 0, byte1.Length);

                // Obtiene la respuesta
                System.Net.WebResponse response = wr.GetResponse();
                // Stream con el contenido recibido del servidor
                newStream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(newStream);
                // Leemos el contenido
                string responseFromServer = reader.ReadToEnd();

                // Cerramos los streams
                reader.Close();
                newStream.Close();
                response.Close();
                return(responseFromServer);
            }
            catch (System.Web.HttpException ex)
            {
                if (ex.ErrorCode == 404)
                {
                    throw new Exception("Not found remote service " + url);
                }
                else
                {
                    throw ex;
                }
            }
        }
コード例 #35
0
        public static string HttpPost(string url, string postData, string contentType, string authorization, ref int statusCode)
        {
            try
            {
                System.Net.WebRequest req = System.Net.WebRequest.Create(url);
                //req.Proxy = new System.Net.WebProxy(ProxyString, true);
                //Add these, as we're doing a POST
                req.ContentType = contentType;
                req.Method      = "POST";
                //We need to count how many bytes we're sending.
                //Post'ed Faked Forms should be name=value&
                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(postData);
                req.ContentLength = bytes.Length;

                if (!string.IsNullOrEmpty(authorization))
                {
                    req.Headers.Add("Authorization", authorization);
                }

                System.IO.Stream os = req.GetRequestStream();
                os.Write(bytes, 0, bytes.Length); //Push it out there
                os.Close();

                System.Net.WebResponse resp = req.GetResponse();
                if (resp == null)
                {
                    return(null);
                }

                System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());

                var response = (HttpWebResponse)req.GetResponse();
                statusCode = response.StatusCode.GetHashCode();

                return(sr.ReadToEnd().Trim());
            }
            catch (WebException ex)
            {
                statusCode = ((HttpWebResponse)ex.Response).StatusCode.GetHashCode();

                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #36
0
ファイル: util.cs プロジェクト: hiepdh/crawler
        public static string HTTP_POST(string Url, string Data)
        {
            string Out = String.Empty;

            System.Net.WebRequest req = System.Net.WebRequest.Create(Url);
            try
            {
                req.Method      = "POST";
                req.Timeout     = 100000;
                req.ContentType = "application/x-www-form-urlencoded";
                byte[] sentData = Encoding.UTF8.GetBytes(Data);
                req.ContentLength = sentData.Length;
                using (System.IO.Stream sendStream = req.GetRequestStream())
                {
                    sendStream.Write(sentData, 0, sentData.Length);
                    sendStream.Close();
                }
                System.Net.WebResponse res           = req.GetResponse();
                System.IO.Stream       ReceiveStream = res.GetResponseStream();
                using (System.IO.StreamReader sr = new System.IO.StreamReader(ReceiveStream, Encoding.UTF8))
                {
                    Char[] read  = new Char[256];
                    int    count = sr.Read(read, 0, 256);

                    while (count > 0)
                    {
                        String str = new String(read, 0, count);
                        Out  += str;
                        count = sr.Read(read, 0, 256);
                    }
                }
            }
            catch (ArgumentException ex)
            {
                Out = string.Format("HTTP_ERROR :: The second HttpWebRequest object has raised an Argument Exception as 'Connection' Property is set to 'Close' :: {0}", ex.Message);
            }
            catch (WebException ex)
            {
                Out = string.Format("HTTP_ERROR :: WebException raised! :: {0}", ex.Message);
            }
            catch (Exception ex)
            {
                Out = string.Format("HTTP_ERROR :: Exception raised! :: {0}", ex.Message);
            }

            return(Out);
        }
コード例 #37
0
        public string Post(string message)
        {
            System.Net.WebRequest req = System.Net.WebRequest.Create(message);
            req.Method      = "POST";
            req.Timeout     = 100000;
            req.ContentType = "application/x-www-form-urlencoded";
            byte[] sentData = Encoding.GetEncoding(1251).GetBytes("");
            req.ContentLength = sentData.Length;
            System.IO.Stream sendStream;
            try
            {
                sendStream = req.GetRequestStream();
                sendStream.Write(sentData, 0, sentData.Length);
                sendStream.Close();
            }
            catch (WebException)
            {
                return("-2");
            }


            System.Net.WebResponse res;
            try
            {
                res = req.GetResponse();
            }
            catch (WebException we)
            {
                return("-3");
            }

            System.IO.Stream       ReceiveStream = res.GetResponseStream();
            System.IO.StreamReader sr            = new System.IO.StreamReader(ReceiveStream, Encoding.UTF8);
            //Кодировка указывается в зависимости от кодировки ответа сервера
            Char[] read  = new Char[256];
            int    count = sr.Read(read, 0, 256);
            string Out   = String.Empty;

            while (count > 0)
            {
                String str = new String(read, 0, count);
                Out  += str;
                count = sr.Read(read, 0, 256);
            }
            return(Out);
        }
コード例 #38
0
        protected void SendNotification(WebRequest request, byte[] payload)
        {
            using (var requestStream = request.GetRequestStream())
            {
                requestStream.Write(payload, 0, payload.Length);
            }

            try
            {
                request.GetResponse();
            }
            catch (WebException ex)
            {
                return;
                /* this happens if certain channels are no longer active */
            }
        }
コード例 #39
0
        private string CheckCRL(string serial)
        {
            string RestCert    = string.Empty;
            string Service_URL = "http://app.ca.tot.co.th/c_service/verify/product_status_checking_result.jsp";

            //ForTEST = 6737
            var Parameters = "issuer=null&searchType=serial&sn=" + serial;

            System.Net.WebRequest req = System.Net.WebRequest.Create(Service_URL);
            req.ContentType = "application/x-www-form-urlencoded";

            req.Method = "POST";
            //We need to count how many bytes we're sending. Post'ed Faked Forms should be name=value&
            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
            req.ContentLength = bytes.Length;

            try
            {
                Stream os = req.GetRequestStream();
                os.Write(bytes, 0, bytes.Length); //Push it out there
                os.Close();

                System.Net.WebResponse resp = req.GetResponse();

                if (resp != null)
                {
                    System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream(), Encoding.Default);
                    Encoding end = sr.CurrentEncoding;
                    RestCert = sr.ReadToEnd().Trim();
                    //if (!string.IsNullOrEmpty(RestCert))
                    //{
                    //    parseHTML(RestCert);
                    //}
                }
            }
            catch (WebException WebEx)
            {
                RestCert = "Error:" + WebEx.Message;
            }
            catch (Exception ex)
            {
                RestCert = "Error:" + ex.Message;
            }
            return(RestCert);
        }
コード例 #40
0
        public string executeWS(tipoRequisicao pTipoRequisicao, string pEndereco, string pData)
        {
            try
            {
                System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                                                                                              System.Security.Cryptography.X509Certificates.X509Chain chain,
                                                                                              System.Net.Security.SslPolicyErrors errors)
                {
                    return(true);
                };

                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                Uri iAddress = new Uri(pEndereco);

                System.Net.WebRequest iRequest = System.Net.WebRequest.Create(iAddress) as HttpWebRequest;
                iRequest.Headers.Add("Authorization", "Basic c2V0VEVGOmNhcmxvc0VkdWFyZG9QaWVyZW4=");

                iRequest.Method      = pTipoRequisicao.ToString();
                iRequest.ContentType = "application/json; charset=utf-8";

                using (Stream s = iRequest.GetRequestStream())
                {
                    using (StreamWriter sw = new StreamWriter(s))
                        sw.Write(pData);
                }

                using (System.Net.HttpWebResponse response = iRequest.GetResponse() as System.Net.HttpWebResponse)
                {
                    System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
                    return(reader.ReadToEnd().Replace("\r", "").Replace("\n", ""));
                }
            }
            catch (WebException we)
            {
                HttpWebResponse errorResponse = we.Response as HttpWebResponse;
                string          r             = new StreamReader(we.Response.GetResponseStream()).ReadToEnd();

                return(r);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #41
0
        public HTMLEnderecoParse(WebRequest requisicao, int cep)
        {
            var bytes = System.Text.Encoding.ASCII.GetBytes(string.Format("cepEntrada={0}&tipoCep=&cepTemp&metodo=buscarCep", cep));
            requisicao.ContentLength = bytes.Length;
            using (var os = requisicao.GetRequestStream())
            {
                os.Write(bytes, 0, bytes.Length);
                os.Close();
            }

            var resposta = requisicao.GetResponse();
            using (var responseStream = resposta.GetResponseStream())
            using (var reader = new StreamReader(responseStream))
            {
                var html = reader.ReadToEnd();
                _csQueryParsed = CQ.Create(html);
            }

            if (EhValido)
            {
                var htmlResp = _csQueryParsed.Select(".respostadestaque");
                Endereco = new Endereco
                {
                    Bairro = htmlResp.Eq(1).Contents().ToHtmlString().Trim()
                    ,
                    Cep = htmlResp.Eq(3).Contents().ToHtmlString().Trim()
                    ,
                    Cidade = htmlResp.Eq(2).Contents().ToHtmlString().Trim().Split('/')[0].Trim()
                    ,
                    Estado = htmlResp.Eq(2).Contents().ToHtmlString().Trim().Split('/')[1].Trim()
                    ,
                    TipoDeLogradouro = htmlResp.Eq(0).Contents().ToHtmlString().Trim().Split(' ')[0]
                };
                var logradouro = htmlResp.Eq(0).Contents().ToHtmlString().Trim().Split(' ');
                var logradouroCompleto = string.Empty;
                for (var i = 0; i < logradouro.Length; i++)
                {
                    if (i <= 0) continue;
                    if (logradouro[i] == "-") break;
                    logradouroCompleto += logradouro[i];
                    logradouroCompleto += " ";
                }
                Endereco.Logradouro = logradouroCompleto.Trim();
            }
        }
コード例 #42
0
        private ResponseData GetPostResponseData(WebRequest request, CrawlingOption option)
        {
            byte[] byteArray = Encoding.UTF8.GetBytes(option.Data);
            request.ContentLength = byteArray.Length;

            // Get the request stream.
            using (var dataStream = request.GetRequestStream())
            {
                // Write the data to the request stream.
                dataStream.Write(byteArray, 0, byteArray.Length);
                // Close the Stream object.
                dataStream.Close();
            }

            // Get the response.
            var response = request.GetResponse();
            return GetResponseData((HttpWebResponse)response);
        }
コード例 #43
0
        public dynamic SendRequest(WebRequest request, object body)
        {
            if (!request.Method.Equals("GET") && body != null)
            {
                using (Stream postStream = request.GetRequestStream())
                {
                    var data = Encoding.UTF8.GetBytes(JObject.FromObject(body).ToString());
                    postStream.Write(data, 0, data.Length);
                }
            }

            using (WebResponse response = request.GetResponse())
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                object def = new { };
                return JsonConvert.DeserializeAnonymousType(reader.ReadToEnd(), def);
            }
        }
コード例 #44
0
        public string HttpPost(string URI, string Parameters)
        {
            try {
                System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
                req.Proxy = new System.Net.WebProxy();

                //Add these, as we're doing a POST
                req.ContentType = "application/x-www-form-urlencoded";
                req.Method      = "POST";

                //We need to count how many bytes we're sending.
                //Post'ed Faked Forms should be name=value&


                byte[] bytes = System.Text.UnicodeEncoding.ASCII.GetBytes(Parameters);
                req.ContentLength = bytes.Length;

                //  log.Info("HttpPost Request Started URI {0} Parameters {1}",URI,Parameters);
                using (System.IO.Stream os = req.GetRequestStream()) {
                    os.Write(bytes, 0, bytes.Length); //Push it out there
                    os.Close();
                }
                //   log.Info("HttpPost Request Finished URI {0} Parameters {1}",URI,Parameters);

                //  log.Info("HttpPost ResponseReading Started URI {0} Parameters {1}",URI,Parameters);
                using (System.Net.WebResponse resp = req.GetResponse()) {
                    string returnedXML = String.Empty;
                    if (resp == null)
                    {
                        return(null);
                    }
                    using (System.IO.StreamReader sr =
                               new System.IO.StreamReader(resp.GetResponseStream())) {
                        returnedXML = sr.ReadToEnd().Trim();
                    }
                    resp.Close();
                    //  log.Info("HttpPost ResponseReading Finished URI {0} Parameters {1}",URI,Parameters);

                    return(returnedXML);
                }
            } catch {
                return("");
            }
        }
コード例 #45
0
ファイル: Network.cs プロジェクト: eai04191/OnPS
        public static string HTTP_POST(string Url, string data, String Authorization = AuthorizationKey)
        {
            string Out      = null;
            var    PostData = Encoding.UTF8.GetBytes(data);

            System.Net.WebRequest request = System.Net.WebRequest.Create(Url);
            if (Authorization != null)
            {
                request.Headers["Authorization"] = Authorization;
            }
            request.Method        = "POST";
            request.ContentType   = "application/x-www-form-urlencoded";
            request.ContentLength = PostData.Length;
            using (var stream = request.GetRequestStream())
            {
                stream.Write(PostData, 0, PostData.Length);
            }
            try
            {
                System.Net.WebResponse resp = request.GetResponse();
                using (System.IO.Stream stream = resp.GetResponseStream())
                {
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(stream))
                    {
                        Out = sr.ReadToEnd();
                        sr.Close();
                    }
                }
            }
            catch (ArgumentException ex)
            {
                Out = string.Format("HTTP_ERROR :: The second HttpWebRequest object has raised an Argument Exception as 'Connection' Property is set to 'Close' :: {0}", ex.Message);
            }
            catch (WebException ex)
            {
                Out = string.Format("HTTP_ERROR :: WebException raised! :: {0}", ex.Message);
            }
            catch (Exception ex)
            {
                Out = string.Format("HTTP_ERROR :: Exception raised! :: {0}", ex.Message);
            }

            return(Out);
        }
コード例 #46
0
        public static void SubmitRealEstateRequest()
        {
            System.Net.WebRequest req = System.Net.WebRequest.Create("https://real-estate-detail.com/market/api");

            req.ConnectionGroupName = REAL_ESTATE_CONN_GROUP;

            var noCachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);//是否把响应缓存起来

            req.CachePolicy = noCachePolicy;

            req.AuthenticationLevel = AuthenticationLevel.MutualAuthRequired;
            req.Credentials         = new NetworkCredential("test_user", "secure_and_safe_password");

            Stream reqStream     = req.GetRequestStream();
            var    messageString = "test";
            var    messageBytes  = Encoding.UTF8.GetBytes(messageString);

            reqStream.Write(messageBytes, 0, messageBytes.Length);
        }
コード例 #47
0
ファイル: Services.cs プロジェクト: rprudnikov-itrf/rosbuh
        public void ОптравитьВСтатистику(string Приложение, string Источник, DateTime Дата, decimal Значение)
        {
            if (Значение == 0)
            {
                return;
            }

            Task.Factory.StartNew(() =>
            {
                try
                {
                    var paramList            = new Dictionary <string, object>();
                    paramList["Application"] = Приложение;
                    paramList["Source"]      = Источник;
                    paramList["Date"]        = Дата.ToString("d");
                    paramList["Value"]       = Значение.ToString();

                    var serverUrl = "http://g.itrf.ru/set.ashx";

                    System.Net.WebRequest req = System.Net.WebRequest.Create(serverUrl);
                    req.Method      = "POST";
                    req.ContentType = "application/x-www-form-urlencoded";
                    req.Timeout     = 30 * 1000;

                    var query = string.Join("&", paramList.Select(p => string.Format("{0}={1}", p.Key, p.Value)).ToArray());

                    byte[] requestBodyBytes = System.Text.Encoding.UTF8.GetBytes(query);

                    req.ContentLength = requestBodyBytes.Length;

                    System.IO.Stream newStream = req.GetRequestStream();
                    newStream.Write(requestBodyBytes, 0, requestBodyBytes.Length);
                    newStream.Close();

                    System.Net.WebResponse response = req.GetResponse();

                    System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
                    reader.ReadToEnd();
                }
                catch { }
            });
        }
コード例 #48
0
ファイル: Core.cs プロジェクト: kaue/movie-rating
    /// <summary>
    /// Send a HTTP Post Request
    /// </summary>
    /// <param name="lUrl"></param>
    /// <param name="lPostData"></param>
    /// <returns></returns>
    public static string HttpPost(string lUrl, string lPostData)
    {
        System.Net.WebRequest webRequest = System.Net.WebRequest.Create(lUrl);
        webRequest.ContentType = "application/x-www-form-urlencoded";
        webRequest.Method      = "POST";
        byte[] bytes = System.Text.Encoding.ASCII.GetBytes(lPostData);
        webRequest.ContentLength = bytes.Length;
        System.IO.Stream os = webRequest.GetRequestStream();
        os.Write(bytes, 0, bytes.Length);
        os.Close();
        System.Net.WebResponse webResponse = webRequest.GetResponse();
        if (webResponse == null)
        {
            return(null);
        }
        System.IO.StreamReader streamReader = new System.IO.StreamReader(webResponse.GetResponseStream());
        string strResponse = streamReader.ReadToEnd().Trim();

        return(strResponse);
    }
コード例 #49
0
 public static string HttpPost(string URI, string Parameters)
 {
     System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
     req.ContentType = "application/x-www-form-urlencoded";
     req.Method      = "POST";
     req.Timeout     = 2000;
     //byte[] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
     byte[] bytes = System.Text.Encoding.UTF8.GetBytes(Parameters);
     req.ContentLength = bytes.Length;
     System.IO.Stream os = req.GetRequestStream();
     os.Write(bytes, 0, bytes.Length); //Push it out there
     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());
 }
コード例 #50
0
ファイル: GcmModel.cs プロジェクト: AlexanderHieser/GCMSender
        public void CheckKeyValidity(string key, string tokenToTest)
        {
            try
            {
                ValidityRequest = HttpWebRequest.Create(Configuration.GCMServerURL);
                ValidityRequest.Method = "post";
                ValidityRequest.Headers.Add(string.Format("Authorization: key={0}", key));
                //Create token Json
                if (!string.IsNullOrEmpty(tokenToTest))
                {
                String[] tokens = tokenToTest.Split(';');

                JObject o = new JObject();
                o.Add("registration_ids", new JArray(tokens));
                ValidityRequest.ContentLength = o.ToString().Length;
                ValidityRequest.ContentType = "application/json";

                using (StreamWriter writer = new StreamWriter(ValidityRequest.GetRequestStream()))
                {
                    writer.Write(o.ToString());
                }
                Console.WriteLine(o.ToString());

                }
                else
                {
                    ValidityRequest.ContentLength = 0;
                }

                HttpWebResponse response = (HttpWebResponse)ValidityRequest.GetResponse();

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    MessageBox.Show("Your token is valid \n ", "Token is valid", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (WebException e)
            {
                MessageBox.Show("Token not valid", "Sorry", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
コード例 #51
0
        //postUpload gets its on function simply because of how differently things are required to be sent
        private string postUpload(string url, NameValueCollection post = null, string uploadDetails = "")
        {
            //Create multiform boundry then initialize the request
            string boundary = "----------" + DateTime.Now.Ticks.ToString("x");

            System.Net.WebRequest webRequest = System.Net.WebRequest.Create(url);
            webRequest.Method      = "POST";
            webRequest.ContentType = "multipart/form-data; boundary=" + boundary;

            //generate multiform header
            string header = boundary + Environment.NewLine +
                            "Content-Disposition: form-data; name=\"uploadfile\"; filename=\"transactions.txt\"" + Environment.NewLine +
                            "Content-Type: text/plain" + Environment.NewLine + Environment.NewLine +

                            uploadDetails + Environment.NewLine +
                            boundary + Environment.NewLine +
                            "Content-Disposition: form-data; name=\"__PAGE_KEY\"" + Environment.NewLine + Environment.NewLine +
                            post["__PAGE_KEY"] + Environment.NewLine +
                            boundary + "--";

            //encode header to bytes
            ASCIIEncoding encoding = new ASCIIEncoding();

            byte[] body = encoding.GetBytes(header);

            //set contentlength header
            webRequest.ContentLength = body.Length;

            //create the stream and write the data
            Stream newStream = webRequest.GetRequestStream();

            newStream.Write(body, 0, body.Length);
            newStream.Close();

            //Get results from stream
            StreamReader sr     = new StreamReader(webRequest.GetResponse().GetResponseStream());
            string       Result = sr.ReadToEnd();

            //done
            return(Result);
        }
コード例 #52
0
        /// <summary>
        /// 上传视频分片的Post请求
        /// </summary>
        /// <param name="url">接口url</param>
        /// <param name="buffer">上传的字符数组</param>
        /// <param name="xNosToken">上传token</param>
        /// <returns>返回响应的json数据</returns>
        public static string HttpPostVideo(string url, byte[] buffer, string xNosToken)
        {
            //得到request
            System.Net.WebRequest request = httpRequestBuilder(url, "POST", xNosToken);

            using (Stream streamWriter = request.GetRequestStream())
            {
                streamWriter.Write(buffer, 0, buffer.Length);
                streamWriter.Flush();
                streamWriter.Close();
            }

            HttpWebResponse response = null;

            try
            {
                // Get the response.
                response = (HttpWebResponse)request.GetResponse();
                // Display the status.
                //Console.WriteLine(response.StatusDescription);
                // Get the stream containing content returned by the server.
                Stream dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                StreamReader reader = new StreamReader(dataStream);
                // Read the content.
                string responseFromServer = reader.ReadToEnd();
                // Display the content.
                // Console.WriteLine(responseFromServer);
                // Cleanup the streams and the response.
                reader.Close();
                dataStream.Close();
                response.Close();
                return(responseFromServer);
            }
            catch (Exception e)
            {
                Console.WriteLine("[HttpPost] fail to get response. " + e.Message);
                Console.WriteLine("[HttpPost] fail to get response. " + response.StatusDescription);
                throw new VcloudException("[HttpPost] fail to get response. " + e.Message);
            }
        }
コード例 #53
0
        public void CreateMultipartRequest(WebRequest request)
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", CultureInfo.InvariantCulture);
            request.ContentType = "multipart/form-data; boundary=" + boundary;

            byte[] byteContent;
            using (var memoryStream = new MemoryStream())
            {

                foreach (var item in _formData)
                {
                    string header = String.Format(CultureInfo.InvariantCulture, FormDataTemplate, boundary, item.Key, item.Value);
                    byte[] headerBytes = Encoding.UTF8.GetBytes(header);
                    memoryStream.Write(headerBytes, 0, headerBytes.Length);

                }

                byte[] newlineBytes = Encoding.UTF8.GetBytes("\r\n");
                foreach (var file in _files)
                {
                    string header = String.Format(CultureInfo.InvariantCulture, FileTemplate, boundary, file.FieldName, file.FieldName, file.ContentType);
                    byte[] headerBytes = Encoding.UTF8.GetBytes(header);
                    memoryStream.Write(headerBytes, 0, headerBytes.Length);
                    using (Stream fileStream = file.FileFactory())
                    {
                        fileStream.CopyTo(memoryStream);
                    }
                    memoryStream.Write(newlineBytes, 0, newlineBytes.Length);
                }
                string trailer = String.Format(CultureInfo.InvariantCulture, "--{0}--", boundary);
                byte[] trailerBytes = Encoding.UTF8.GetBytes(trailer);
                memoryStream.Write(trailerBytes, 0, trailerBytes.Length);

                byteContent = memoryStream.ToArray();
            }
            request.ContentLength = byteContent.Length;
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(byteContent, 0, (int)byteContent.Length);
            }
        }
コード例 #54
0
        internal static string Reqest(string method, string url, Dictionary <string, object> parameters)
        {
            try
            {
                /*
                 * //设定安全协议为安全套接字层(SSL)3.0协议
                 * if (url.ToLower().IndexOf("https://") >= 0)
                 *  ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
                 */
                System.Net.WebRequest httpRquest = System.Net.HttpWebRequest.Create(url);
                httpRquest.Method = method; // "POST";
                                            //这行代码很关键,不设置ContentType将导致后台参数获取不到值
                                            //httpRquest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";


                //写入请求流
                if (null != parameters)
                {
                    httpRquest.ContentType = "application/x-www-form-urlencoded";
                    using (Stream stream = httpRquest.GetRequestStream())
                    {
                        foreach (KeyValuePair <string, object> item in parameters)
                        {
                            byte[] formBytes = System.Text.Encoding.UTF8.GetBytes(string.Format("{0}={1}", item.Key, item.Value));
                            stream.Write(formBytes, 0, formBytes.Length);
                        }
                        stream.Close();
                    }
                }
                System.Net.WebResponse response       = httpRquest.GetResponse();
                System.IO.Stream       responseStream = response.GetResponseStream();
                System.IO.StreamReader reader         = new System.IO.StreamReader(responseStream, System.Text.Encoding.UTF8);
                string responseContent = reader.ReadToEnd();
                return(responseContent);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(" Error: " + ex.Message);
            }
            return("");
        }
コード例 #55
0
        /**
         * 通用接口发短信
         * @param text 短信内容 
         * @param mobile 接受的手机号
         * @return json格式字符串
         */
        public static string sendSms(string apikey, string text, string mobile)
        {
            //注意:参数必须进行Uri.EscapeDataString编码。以免&#%=等特殊符号无法正常提交
            string parameter = "apikey=" + apikey + "&text=" + Uri.EscapeDataString(text) + "&mobile=" + mobile;

            System.Net.WebRequest req = System.Net.WebRequest.Create(URI_SEND_SMS);
            req.ContentType = "application/x-www-form-urlencoded";
            req.Method      = "POST";
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(parameter);    //这里编码设置为utf8
            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());
        }
コード例 #56
0
ファイル: DiagrammTSG.aspx.cs プロジェクト: maziesmith/KOS
        private static XmlDocument POST(string Url, string Data)
        {
            System.Net.WebRequest req = System.Net.WebRequest.Create(Url);
            req.Method      = "POST";
            req.Timeout     = 100000;
            req.ContentType = "application/x-www-form-urlencoded";
            // UTF8Encoding encoding = new UTF8Encoding();
            byte[] sentData = Encoding.GetEncoding(1251).GetBytes(Data);
            req.ContentLength = sentData.Length;
            System.IO.Stream sendStream = req.GetRequestStream();
            sendStream.Write(sentData, 0, sentData.Length);
            sendStream.Close();
            System.Net.WebResponse res           = req.GetResponse();
            System.IO.Stream       ReceiveStream = res.GetResponseStream();
            System.IO.StreamReader sr            = new System.IO.StreamReader(ReceiveStream, Encoding.UTF8);
            //Кодировка указывается в зависимости от кодировки ответа сервера
            XmlDocument doc = new XmlDocument();

            doc.Load(sr);
            return(doc);
        }
コード例 #57
0
        /**
         * 模板接口发短信
         * @param tpl_id 模板id
         * @param tpl_value 模板变量值
         * @param mobile 接受的手机号
         * @return json格式字符串
         */
        public static string tplSendSms(string apikey, long tpl_id, string tpl_value, string mobile)
        {
            string encodedTplValue = Uri.EscapeDataString(tpl_value);
            string parameter       = "apikey=" + apikey + "&tpl_id=" + tpl_id + "&tpl_value=" + encodedTplValue + "&mobile=" + mobile;

            System.Net.WebRequest req = System.Net.WebRequest.Create(URI_TPL_SEND_SMS);
            req.ContentType = "application/x-www-form-urlencoded";
            req.Method      = "POST";
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(parameter);    //这里编码设置为utf8
            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());
        }
コード例 #58
0
 public static string HttpPost(string URI, string Parameters, string ProxyString = null)
 {
     System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
     req.Proxy = new System.Net.WebProxy(ProxyString, true);
     //Add these, as we're doing a POST
     req.ContentType = "application/x-www-form-urlencoded";
     req.Method      = "POST";
     //We need to count how many bytes we're sending. Post'ed Faked Forms should be name=value&
     byte[] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
     req.ContentLength = bytes.Length;
     System.IO.Stream os = req.GetRequestStream();
     os.Write(bytes, 0, bytes.Length); //Push it out there
     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());
 }
コード例 #59
0
ファイル: CalDavClient.cs プロジェクト: flom/caldavclient
    private HttpWebResponse SendRequest(WebRequest request, byte[] data)
    {
      request.ContentLength = data.Length;
      using (Stream stream = request.GetRequestStream())
      {
        stream.Write(data, 0, data.Length);
      }

      return (HttpWebResponse)request.GetResponse();
    }
コード例 #60
0
 private static void writeAssemblyNameToRequest(WebRequest req, byte[] assemblyBuf)
 {
     req.ContentLength = assemblyBuf.Length;
     using (var stream = req.GetRequestStream())
         stream.Write(assemblyBuf, 0, assemblyBuf.Length);
 }