コード例 #1
0
 private string GetHttp(string a_strUrl, int timeout)
 {
     try
     {
         string AUrl = a_strUrl;
         System.Net.HttpWebRequest myReq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(AUrl);
         myReq.Timeout = timeout;
         System.Net.HttpWebResponse HttpWResp = (System.Net.HttpWebResponse)myReq.GetResponse();
         System.IO.Stream           myStream  = HttpWResp.GetResponseStream();
         System.IO.StreamReader     sr        = new System.IO.StreamReader(myStream, Encoding.UTF8);
         StringBuilder sb = new StringBuilder();
         while (!sr.EndOfStream)
         {
             sb.AppendLine(sr.ReadLine());
         }
         return(sb.ToString());
     }
     catch (Exception exp)
     {
         return("错误:" + exp.Message);
     }
 }
コード例 #2
0
        public static void DownLoadFile(string url, string filename)
        {
            System.Net.HttpWebRequest  Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
            System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
            long totalBytes = myrp.ContentLength;

            System.IO.Stream st = myrp.GetResponseStream();
            System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
            long             totalDownloadedByte = 0;

            byte[] by    = new byte[1024];
            int    osize = st.Read(by, 0, (int)by.Length);

            while (osize > 0)
            {
                totalDownloadedByte = osize + totalDownloadedByte;
                so.Write(by, 0, osize);
                osize = st.Read(by, 0, (int)by.Length);
            }
            so.Close();
            st.Close();
        }
コード例 #3
0
        public static Stream ProcessCommand(string strURI, string strHttpCommand, Stream streamContent)
        {
            try
            {
                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 = streamContent.Length;

                Stream reqStream = request.GetRequestStream();

                byte[] inData = new byte[streamContent.Length];

                int bytesRead = streamContent.Read(inData, 0, (int)streamContent.Length);

                reqStream.Write(inData, 0, (int)streamContent.Length);

                streamContent.Close();

                System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();

                reqStream.Close();

                return(response.GetResponseStream());
            }
            catch (System.Net.WebException webex)
            {
                throw new Exception(webex.Message);
            }
            catch (Exception Ex)
            {
                throw new Exception(Ex.Message);
            }
        }
コード例 #4
0
        /// <summary>
        /// 获取支付宝远程服务器ATN结果,验证是否是支付宝服务器发来的请求
        /// </summary>
        /// <param name="URLStr">请求URL地址,需带通知的ID,partnerID等参数</param>
        /// <returns>返回true是正确的信息,false是无效的</returns>
        private string VerificationHttp(string URLStr)
        {
            System.Text.StringBuilder strBuilder = new System.Text.StringBuilder();
            try
            {
                System.Net.HttpWebRequest myReq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URLStr);
                myReq.Timeout = 120000;//超时时间
                System.Net.HttpWebResponse HttpWResp = (System.Net.HttpWebResponse)myReq.GetResponse();
                System.IO.Stream           myStream  = HttpWResp.GetResponseStream();
                System.IO.StreamReader     sr        = new System.IO.StreamReader(myStream, Encoding.Default);
                while (-1 != sr.Peek())
                {
                    strBuilder.Append(sr.ReadLine());
                }
            }
            catch (Exception exp)
            {
                strBuilder.Append("错误:" + exp.Message);
            }

            return(strBuilder.ToString());
        }
コード例 #5
0
ファイル: Convert.cs プロジェクト: GitHub-XK/Heron
        //////////////////////////////////////////////////////


        //////////////////////////////////////////////////////
        ///TODO: Converting Rhino/GH geometry type to GDAL geometry types
        ///
        //////////////////////////////////////////////////////


        public static string HttpToJson(string URL)
        {
            //need to update for https issues
            //GH forum issue: https://www.grasshopper3d.com/group/heron/forum/topics/discover-rest-data-sources?commentId=2985220%3AComment%3A1945956&xg_source=msg_com_gr_forum
            //solution found here: https://stackoverflow.com/questions/2859790/the-request-was-aborted-could-not-create-ssl-tls-secure-channel
            //add these two lines of code
            System.Net.ServicePointManager.Expect100Continue = true;
            System.Net.ServicePointManager.SecurityProtocol  = System.Net.SecurityProtocolType.Tls12;

            //get json from rest service
            System.Net.HttpWebRequest req = System.Net.WebRequest.Create(URL) as System.Net.HttpWebRequest;
            string result = null;

            using (System.Net.HttpWebResponse resp = req.GetResponse() as System.Net.HttpWebResponse)
            {
                System.IO.StreamReader reader = new System.IO.StreamReader(resp.GetResponseStream());
                result = reader.ReadToEnd();
                reader.Close();
            }

            return(result);
        }
コード例 #6
0
        public Stream ProcessCommand(string strURI, string strHttpCommand)
        {
            try
            {
                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 = 0;
                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);
            }
        }
コード例 #7
0
        public static string GenerateResponseXMl(string url)
        {
            string _responseString = string.Empty;

            System.Net.HttpWebRequest request1 = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            request1.Method = "GET";
            request1.Accept = "*/*";
            System.Net.HttpWebResponse wResponse         = (System.Net.HttpWebResponse)request1.GetResponse();
            System.IO.StreamReader     strresponseReader = null;
            strresponseReader = new System.IO.StreamReader(wResponse.GetResponseStream());
            _responseString   = strresponseReader.ReadToEnd();

            if (_responseString == string.Empty)
            {
                _responseString = wResponse.StatusDescription;
            }

            _responseString = _responseString.Replace("xmlns=\"http://schemas.datacontract.org/2004/07/\"", "");
            _responseString = _responseString.Replace("xmlns=\"\"", "");

            return(_responseString);
        }
コード例 #8
0
 public void cargarJson(string url, System.Collections.ArrayList headers, string post = null, string content_type = "application/x-www-form-urlencoded")
 {
     try {
         System.Net.HttpWebRequest      solicitud = (System.Net.HttpWebRequest)System.Net.WebRequest.CreateDefault(new Uri(url));
         System.Net.WebHeaderCollection cabeceras = new System.Net.WebHeaderCollection();
         foreach (string cabecera in headers)
         {
             if (cabecera.IndexOf("Accept") == 0)
             {
                 string[] partes = cabecera.Split(new char[] { ':' }, 2);
                 solicitud.Accept = partes[1].Trim();
             }
             else
             {
                 cabeceras.Add(cabecera);
             }
         }
         solicitud.Headers = cabeceras;
         if (post != null)
         {
             solicitud.Method      = "POST";
             solicitud.ContentType = content_type;
             byte[] buffer = new byte[post.Length];
             //post.
             for (int i = 0; i < post.Length; i++)
             {
                 buffer[i] = (byte)(post[i]);
             }
             System.IO.Stream datos = solicitud.GetRequestStream();
             datos.Write(buffer, 0, post.Length);
         }
         System.Net.HttpWebResponse respuesta = (System.Net.HttpWebResponse)solicitud.GetResponse();
         string json_texto = leerStream(respuesta.GetResponseStream());
         parse(json_texto);
     }catch (Exception ex) {
         System.Diagnostics.Trace.WriteLine("ERROR AL CARGAR JSON. \r\n" + ex.Message);
     }
 }
コード例 #9
0
        private bool GetResponseFromServer(String sURL, out String sResponse)
        {
            try
            {
                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(sURL);

                System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();

                Trace.TraceInformation("Content type is {0} and length is {1}", response.ContentType, response.ContentLength);

                System.IO.Stream stream = response.GetResponseStream();

                // Pipes the stream to a higher level stream reader with the required encoding format.
                System.IO.StreamReader streamReader = new System.IO.StreamReader(stream, Encoding.UTF8);

                sResponse = streamReader.ReadToEnd();

                streamReader.Close();
                streamReader.Dispose();
                streamReader = null;

                stream.Close();
                stream.Dispose();
                stream = null;

                response.Close();
                response = null;
                request  = null;

                return(true);
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("Exception: " + ex.Message + Environment.NewLine + "Stacktrace: " + ex.StackTrace);
                sResponse = String.Empty;
                return(false);
            }
        }
コード例 #10
0
        public void DownloadFile(string URL, String filename, System.Windows.Forms.ToolStripProgressBar prog)
        {
            try
            {
                System.Net.HttpWebRequest  Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                long totalBytes = myrp.ContentLength;

                if (prog != null)
                {
                    prog.Maximum = (int)totalBytes;
                }

                System.IO.Stream st = myrp.GetResponseStream();
                System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                long             totalDownloadedByte = 0;
                byte[]           by = new byte[1024];
                int osize           = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    System.Windows.Forms.Application.DoEvents();
                    so.Write(by, 0, osize);

                    if (prog != null)
                    {
                        prog.Value = (int)totalDownloadedByte;
                    }
                    osize = st.Read(by, 0, (int)by.Length);
                }
                so.Close();
                st.Close();
            }
            catch (System.Exception)
            {
                throw;
            }
        }
コード例 #11
0
        void Application_End(object sender, EventArgs e)
        {
            if (!bClearRegisterRoute)
            {
                //在应用程序关闭时运行的代码
                System.Threading.Thread.Sleep(1000);

                string url = "http://localhost/SmartLife.CertManage.ManageServices/AppShare/forReStart.ashx"; //测试
                if (GlobalManager.CurrentDeployNode != null && GlobalManager.CurrentDeployNode.RunMode != 1)
                {                                                                                             //正式
                    url = GlobalManager.CurrentDeployNode.AccessPoint + "/AppShare/forReStart.ashx";
                }
                if (GlobalManager.CurrentDeployNode == null && GlobalManager.DeployNodes != null && GlobalManager.DeployNodes.Count > 0)
                {
                    //GlobalManager.CurrentDeployNode 为空,IIS已回收过
                    url = GlobalManager.DeployNodes.FirstOrDefault(s => s.RunMode == 0).AccessPoint + "/AppShare/forReStart.ashx";
                }

                System.Net.HttpWebRequest  myHttpWebRequest  = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                System.Net.HttpWebResponse myHttpWebResponse = (System.Net.HttpWebResponse)myHttpWebRequest.GetResponse();
                System.IO.Stream           receiveStream     = myHttpWebResponse.GetResponseStream();//得到回写的字节流
            }
        }
コード例 #12
0
ファイル: CheckUpdates.cs プロジェクト: daisy/obi
        private string GetReleaseInfoFileContents()
        {
            Uri releaseInfoFileUri = new Uri("https://dl.daisy.org/tools/Obi/latest-release.txt");

            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)
                                                System.Net.WebRequest.Create(releaseInfoFileUri);
            System.Net.HttpWebResponse response =
                (System.Net.HttpWebResponse)request.GetResponse();
            string s = null;

            try
            {
                System.IO.Stream       receiveStream = response.GetResponseStream();
                System.IO.StreamReader strReader     =
                    new System.IO.StreamReader(receiveStream, Encoding.UTF8);
                s = strReader.ReadToEnd();
            }
            finally
            {
                response.Close();
            }
            return(s);
        }
コード例 #13
0
ファイル: HttpUtil.cs プロジェクト: zhangshourui/reartools
        public static string GetHttpGetString(string url, ContentType contentType = ContentType.text_plain)
        {
            try
            {
                System.Net.HttpWebRequest myRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                myRequest.Method = "GET";

                myRequest.ContentType = contentType.ToContentTypeStr();
                myRequest.Proxy       = null;

                // 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);
            }
        }
コード例 #14
0
ファイル: FacebookHelper.cs プロジェクト: woludhe/sema
        private string GetAccessToken(string code)
        {
            //Notice the empty redirect_uri! And the replace on the code we get from the cookie.
            string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}", _appId, "", _appSecret, code.Replace("\"", ""));

            System.Net.HttpWebRequest  request  = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest;
            System.Net.HttpWebResponse response = null;

            try
            {
                using (response = request.GetResponse() as System.Net.HttpWebResponse)
                {
                    System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());

                    string retVal = reader.ReadToEnd();
                    return(retVal);
                }
            }
            catch
            {
                return(null);
            }
        }
コード例 #15
0
ファイル: 58.cs プロジェクト: lamebits/meiwenwang_news
        public void ChangeResultDic(Dictionary <string, string> dic)
        {
            if (dic.ContainsKey("手机号码") && dic["手机号码"].StartsWith("http://", StringComparison.OrdinalIgnoreCase))
            {
                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(dic["手机号码"]);
                request.Method = "GET";
                System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();

                System.IO.Stream sm = response.GetResponseStream();
                try
                {
                    System.Drawing.Image img = System.Drawing.Image.FromStream(sm);
                    dic["手机号码"] = Ocr3.Process((Bitmap)img);
                }
                catch
                {
                }
            }
            else if (dic.ContainsKey("文字电话") && dic.ContainsKey("手机号码"))
            {
                dic["手机号码"] = dic["文字电话"];
            }
        }
コード例 #16
0
ファイル: API.cs プロジェクト: dtsonvt/IPC247
        public static string API_GET_Rep(string LinkAPI)
        {
            string jsonretun = "";

            try
            {
                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(LinkAPI);
                request.KeepAlive       = false;
                request.ProtocolVersion = System.Net.HttpVersion.Version10;
                request.Method          = "GET";
                request.Timeout         = 60000;
                System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
                using (StreamReader rdr = new StreamReader(response.GetResponseStream()))
                {
                    jsonretun = rdr.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                API.API_ERRORLOG(new ERRORLOG(Form_Main.IPAddress, "API", "API_GET_Rep()", ex.ToString()));
            }
            return(jsonretun.Replace("=0=", "\r\n"));
        }
コード例 #17
0
ファイル: GoogleFolder.cs プロジェクト: ljm3994/CloudManager
        public async Task <CloudFiles> CreateFolder(string foldername, string parentid)
        {
            string method = "POST";
            string uri    = "https://www.googleapis.com/drive/v2/files";
            object parent;

            parent = new object[] { new { id = parentid } };
            UniValue properties = UniValue.Create(new { title = foldername, parents = parent, mimeType = "application/vnd.google-apps.folder" });

            try
            {
                byte[] buf = Encoding.UTF8.GetBytes(properties.ToString());
                System.Net.HttpWebResponse rp = await HttpHelper.RequstHttp(method, uri, null, driveinfo.token.access_token, null, buf, buf.Length, 0, buf.Length);

                Dictionary <string, object> dic = HttpHelper.DerealizeJson(rp.GetResponseStream());
                CloudFiles file = AddFiles(dic);
                return(file);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
コード例 #18
0
        /// <summary>
        /// 下载文件(显示进度)
        /// </summary>
        /// <param name="url"></param>
        /// <param name="filename"></param>
        public void DownloadImageFile(string url, string filename)
        {
            Stream so = new FileStream(filename, FileMode.Create);
            Stream st = null;

            try
            {
                System.Net.HttpWebRequest myrq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                //等待五分钟
                myrq.Timeout = 300000;
                System.Net.HttpWebResponse myra = (System.Net.HttpWebResponse)myrq.GetResponse();
                st = myra.GetResponseStream();
                long   totalDownloadedByte = 0;
                byte[] by = new byte[1024];
                if (st != null)
                {
                    int size = st.Read(by, 0, by.Length);
                    while (size > 0)
                    {
                        totalDownloadedByte = size + totalDownloadedByte;
                        Application.DoEvents();
                        so.Write(@by, 0, size);
                        size = st.Read(@by, 0, @by.Length);
                    }
                }
            }
            catch (Exception e)
            {
                LogHelper.ErrorLog(ErrorCode.DownImgError, e);
                MessageBox.Show(ErrorCode.DownImgError, ErrorCode.Caption);
            }
            finally
            {
                so.Close();
                st?.Close();
            }
        }
コード例 #19
0
        /// <summary>
        /// 从谷歌官方api获取发音并下载到本地,返回音频文件相对路径
        /// </summary>
        /// <param name="word">单词全拼</param>
        /// <returns>返回音频文件相对路径</returns>
        private static string makeMp3(string word)
        {
            try
            {
                string url  = "http://translate.google.com/translate_tts?tl=en&q=" + word;
                string k    = word.Substring(0, 1);
                string path = Directory.CreateDirectory("wordVolice/") + "\\" + k;
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);//在根目录下建立文件夹
                }
                string filename = path + "\\" + word + ".mp3";


                System.Net.HttpWebRequest  Myrq      = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
                System.Net.HttpWebResponse myrp      = (System.Net.HttpWebResponse)Myrq.GetResponse();
                long             totalBytes          = myrp.ContentLength;
                System.IO.Stream st                  = myrp.GetResponseStream();
                System.IO.Stream so                  = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                long             totalDownloadedByte = 0;
                byte[]           by                  = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    so.Write(by, 0, osize);
                    osize = st.Read(by, 0, (int)by.Length);
                }
                so.Close();
                st.Close();
                return("/wordVolice/" + k + "/" + word + ".mp3");
            }
            catch
            {
                return(null);
            }
        }
コード例 #20
0
ファイル: Form1.cs プロジェクト: tonyshen277/Music-Downloader
        public void DownloadFile(string URL, string filename, System.Windows.Forms.ProgressBar prog)
        {
            float percent = 0;

            try
            {
                System.Net.HttpWebRequest  Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                long totalBytes = myrp.ContentLength;
                if (prog != null)
                {
                    prog.Maximum = (int)totalBytes;
                }
                System.IO.Stream st = myrp.GetResponseStream();
                System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                long             totalDownloadedByte = 0;
                byte[]           by = new byte[1024];
                int osize           = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    so.Write(by, 0, osize);
                    if (prog != null)
                    {
                        prog.Value = (int)totalDownloadedByte;
                    }
                    osize   = st.Read(by, 0, (int)by.Length);
                    percent = (float)totalDownloadedByte / (float)totalBytes * 100;
                }
                so.Close();
                st.Close();
            }
            catch (System.Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
コード例 #21
0
 public static string FetchData(string url, int i = 0)
 {
     if (!url.StartsWith("http"))
     {
         url = "http://wiki.answers.com" + url;
     }
     try
     {
         System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
         req.Timeout   = 30000;
         req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22";
         req.Accept    = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
         req.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3");
         req.Headers.Add("Accept-Encoding: gzip,deflate,sdch");
         req.Headers.Add("Accept-Language: en-US,en;q=0.8,fa;q=0.6");
         req.AutomaticDecompression = System.Net.DecompressionMethods.Deflate | System.Net.DecompressionMethods.GZip;
         using (System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)req.GetResponse())
         {
             System.IO.StreamReader reader = new StreamReader(res.GetResponseStream());
             string str = reader.ReadToEnd();
             reader.Close();
             reader.Dispose();
             FileDownloaded++;
             return(str);
         }
     }
     catch (Exception)
     {
         System.Threading.Thread.Sleep(100000);
         i++;
         if (i == 4)
         {
             return("");
         }
         return(FetchData(url, i));
     }
 }
コード例 #22
0
        public static string RemoteVersion(string url)
        {
            string rv = "";

            try {
                System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)
                                                System.Net.WebRequest.Create(url);
                System.Net.HttpWebResponse response      = (System.Net.HttpWebResponse)req.GetResponse();
                System.IO.Stream           receiveStream = response.GetResponseStream();
                System.IO.StreamReader     readStream    = new System.IO.StreamReader(receiveStream, Encoding.UTF8);
                string s = readStream.ReadToEnd();
                response.Close();
                if (ValidateFile(s))
                {
                    rv = s;
                }
            } catch (Exception) {
                // Anything could have happened here but
                // we don't want to stop the user
                // from using the application.
                rv = null;
            }
            return(rv);
        }
コード例 #23
0
        /// <summary>
        /// Handles the response from server
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        public bool GetResponse(System.Net.HttpWebResponse response)
        {
            string enc = "utf-8"; // default

            if (response.ContentEncoding != String.Empty)
            {
                // Use the HttpHeader Content-Type in preference to the one set in META
                this.Encoding = response.ContentEncoding;
            }
            else
            {
                this.Encoding = enc; // default
            }

            System.IO.StreamReader stream = new System.IO.StreamReader
                                                (response.GetResponseStream(), System.Text.Encoding.GetEncoding(this.Encoding));

            //store final URl if it was a redirect
            this.PageToRetrieve = response.ResponseUri;
            this.Length         = response.ContentLength;
            this.Content        = stream.ReadToEnd();
            stream.Close();
            return(true); //success
        }
コード例 #24
0
ファイル: ReversalPG.cs プロジェクト: himanshujoshi19/Test
        public static string FetchDATA(string RequestData)
        {
            try
            {
                Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Information Send to HDFC Gateway : " + RequestData);

                /* This is Payment Gateway Test URL where merchant sends request. This is test enviornment URL,
                 * production URL will be different and will be shared by Bank during production movement */
                string url = HDFCTransUrl;
                System.IO.StreamWriter myWriter = null;
                // it will open a http connection with provided url
                System.Net.HttpWebRequest objRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);//send data using objxmlhttp object
                objRequest.Method        = "POST";
                objRequest.ContentLength = RequestData.Length;
                objRequest.ContentType   = "application/x-www-form-urlencoded";//to set content type
                myWriter = new System.IO.StreamWriter(objRequest.GetRequestStream());
                myWriter.Write(RequestData);
                myWriter.Close();

                string TranInqResponse;
                System.Net.HttpWebResponse objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();
                using (System.IO.StreamReader sr = new System.IO.StreamReader(objResponse.GetResponseStream()))
                {
                    /* The variable declartion where PG response wil be received*/
                    TranInqResponse = sr.ReadToEnd();
                    //receive the responce from objResponse object
                    Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Information Received from HDFC Gateway : " + TranInqResponse);
                    return(TranInqResponse);
                }
            }
            catch (Exception ex)
            {
                Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Exception While Hit HDFC GATEWAY: " + ex);
                return("");
            }
        }
コード例 #25
0
        public void DoDownload(string url, string fileName)
        {
            //WebRequestを作成
            System.Net.HttpWebRequest webreq =
                (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);

            //サーバーからの応答を受信するためのWebResponseを取得
            System.Net.HttpWebResponse webres =
                (System.Net.HttpWebResponse)webreq.GetResponse();

            //応答データを受信するためのStreamを取得
            System.IO.Stream strm = webres.GetResponseStream();

            //ファイルに書き込むためのFileStreamを作成
            System.IO.FileStream fs = new System.IO.FileStream(
                fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);

            //応答データをファイルに書き込む
            byte[] readData = new byte[1024];
            for (;;)
            {
                //データを読み込む
                int readSize = strm.Read(readData, 0, readData.Length);
                if (readSize == 0)
                {
                    //すべてのデータを読み込んだ時
                    break;
                }
                //読み込んだデータをファイルに書き込む
                fs.Write(readData, 0, readSize);
            }

            //閉じる
            fs.Close();
            strm.Close();
        }
コード例 #26
0
        public static Stream ProcessCommand(string strURI, string strHttpCommand, string strContent, string ContentType = "xml")
        {
            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;
                if (ContentType.ToLower() == "xml")
                {
                    request.ContentType = "application/xml";
                }
                else
                {
                    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);
            }
        }
コード例 #27
0
        private string GetIP()
        {
            Uri uri = new Uri("http://www.ikaka.com/ip/index.asp");

            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();
            System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(s, @"\d+.\d+.\d+.\d+");
            if (m.Success)
            {
                return(m.Groups[0].Value);
            }
            return(string.Empty);
        }
コード例 #28
0
        public static DataModels.DeviceModel getDeviceById(string id)
        {
            string api = "http://localhost:5000/api/devices/" + id;

            System.Net.HttpWebRequest _httpReq =
                System.Net.WebRequest.CreateHttp(api);
            _httpReq.Method = "GET";
            System.Net.HttpWebResponse response = _httpReq.GetResponse() as System.Net.HttpWebResponse;

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine("Communication Successful");
                Console.WriteLine(response.ContentType);
                Console.WriteLine(response.ContentLength);

                System.Runtime.Serialization.Json.DataContractJsonSerializer _jsonSerializer =
                    new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(DataModels.DeviceModel));
                DataModels.DeviceModel m =
                    _jsonSerializer.ReadObject(response.GetResponseStream()) as DataModels.DeviceModel;
                return(m);
            }

            return(null);
        }
コード例 #29
0
ファイル: DropBoxFile.cs プロジェクト: ljm3994/CloudManager
        public async Task CopyFile(FileInfo parentfile)
        {
            string method = "POST";
            string path   = parentfile.FileID;
            string uri    = string.Format("https://api.dropbox.com/1/fileops/copy");
            Dictionary <string, string> parameter = new Dictionary <string, string>();
            string topath = path + "/" + Item.FileName;

            parameter.Add("root", "auto");
            parameter.Add("from_path", Item.FileID);
            parameter.Add("to_path", topath);
            try
            {
                System.Net.HttpWebResponse rp = await HttpHelper.RequstHttp(method, uri, parameter, Item.driveinfo.token.access_token);

                Dictionary <string, object> result = HttpHelper.DerealizeJson(rp.GetResponseStream());
            }
            catch (System.Net.WebException e)
            {
                Dictionary <string, object> result = HttpHelper.DerealizeJson(e.Response.GetResponseStream());
                throw e;
            }
            return;
        }
コード例 #30
0
ファイル: face.cs プロジェクト: jurejoy/EmotionDetectBot
        byte[] getImageFromUrl(string url)
        {
            System.Net.HttpWebRequest  request  = null;
            System.Net.HttpWebResponse response = null;
            byte[] b = null;

            request  = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            response = (System.Net.HttpWebResponse)request.GetResponse();

            if (request.HaveResponse)
            {
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    Stream receiveStream = response.GetResponseStream();
                    using (BinaryReader br = new BinaryReader(receiveStream))
                    {
                        b = br.ReadBytes(500000);
                        br.Close();
                    }
                }
            }

            return(b);
        }