UploadData() public method

public UploadData ( System address, byte data ) : byte[]
address System
data byte
return byte[]
コード例 #1
4
        public String ExecutePost()
        {
            Random rd = new Random();
            int rd_i = rd.Next();
            String nonce = Convert.ToString(rd_i);

            String timestamp = Convert.ToString(ConvertDateTimeInt(DateTime.Now));

            String signature = GetHash(this.appSecret + nonce + timestamp);

            //ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate;
            //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

            WebClient myWebClient = new WebClient();

            myWebClient.Headers.Add("App-Key", this.appkey);
            myWebClient.Headers.Add("Nonce", nonce);
            myWebClient.Headers.Add("Timestamp", timestamp);

            myWebClient.Headers.Add("Signature", signature);

            myWebClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

            byte[] byteArray = Encoding.UTF8.GetBytes(this.postStr);

            byte[] responseArray = myWebClient.UploadData(this.methodUrl, "POST", byteArray);

            return Encoding.UTF8.GetString(responseArray);
        }
コード例 #2
0
        public static string CreateNew(string courseName, string courseNumber, string sectionNumber, string onBehalf)
        {
            string retStr = "";

            WebClient restClient = new WebClient();
            restClient.Headers.Add("Content-Type", Global.ASSITments_ContentType);

            String AuthOnBehalf = "partner=" + "\"" + "Hien-Ref" + "\",onBehalfOf=" + "\"" + onBehalf + "\"";
            restClient.Headers.Add("assistments-auth", AuthOnBehalf);

            string createClassURL = String.Format("{0}/student_class", Global.ASSITmentsBaseAPI);

            //string postData = "{" + "\"" + "courseName" + "\"" + ":" + "\"" + courseName + "\"" + "," +
            //          "\"" + "courseNumber" + "\"" + ":" + "\"" + courseNumber + "\"" + "," +
            //          "\"" + "sectionNumber" + "\"" + ":" + "\"" + sectionNumber + "\"" + "}";

            string postData = "{" + "\"" + "courseName" + "\"" + ":" + "\"" + courseName + "\"" + "}";

            byte[] byteArray = Encoding.ASCII.GetBytes(postData);
            byte[] byteResult = restClient.UploadData(createClassURL, "POST", byteArray);
            retStr = Encoding.ASCII.GetString(byteResult);

            JObject response = JObject.Parse(retStr);
            string classRef = response["class"].ToString();

            return classRef;
        }
コード例 #3
0
ファイル: Upload.cs プロジェクト: baofengcloud/csharp-sdk
        public static String RequestUploadUrl(String json)
        {
            var client = new System.Net.WebClient();

            client.Headers.Add("Content-Type", "application/json");
            var resp = client.UploadData(Const.UploadRequestUrl, "POST",
                                         System.Text.Encoding.UTF8.GetBytes(json));

            var respStr = System.Text.Encoding.UTF8.GetString(resp);

            var result = SimpleJsonParser.Parse(respStr);;

            int    status = 99;
            String errMsg = "";

            if (result.ContainsKey("status"))
            {
                status = int.Parse(result["status"]);
                if (status == 0)
                {
                    return(result["url"]);
                }
            }

            if (result.ContainsKey("errmsg"))
            {
                errMsg = result["errmsg"];
            }

            throw new CloudException(status, errMsg);
        }
コード例 #4
0
        protected void ASSITments_CreateAssignment(object sender, EventArgs e)
        {
            WebClient restClient = new WebClient();
            restClient.Headers.Add("Content-Type", Global.ASSITments_ContentType);
            // restClient.Headers.Add("assistments-auth", "partner=" + "\"" + "Hien-Ref" + "\",onBehalfOf=" + Session["OnBehalfOf"]); //Session["OnBehalfOf"]: linkUser.aspx
            restClient.Headers.Add("assistments-auth", Global.ASSITments_Auth_Behalf);
            if (Global.OnBehalfOf == "")
            {
                this.lblASSIT_AssignmentError.Visible = true;
                return;
            }

            string createAssignmentURL = String.Format("{0}/assignment",Global.ASSITmentsBaseAPI);

            string postData = "{" + "\"" + "problemSet" + "\"" + ":" + "\"" + Global.problemSetId + "\"" + "," +
                      "\"" + "class" + "\"" + ":" + "\"" + Global.classRef + "\"" + "," +
                      "\"" + "scope" + "\"" + ":" + "\"" + Global.classRef + "\"" + "}";
            byte[] byteArray = Encoding.ASCII.GetBytes(postData);
            byte[] byteResult = restClient.UploadData(createAssignmentURL, "POST", byteArray);
            string retStr = Encoding.ASCII.GetString(byteResult);

            JObject response = JObject.Parse(retStr);
            string assignment_ref = response["assignment"].ToString();
            Global.assignmentRef = assignment_ref;
            this.lblASSIT_AssignmentOK.Visible = true;
        }
コード例 #5
0
ファイル: UsernameUUID.cs プロジェクト: mctraveler/MineSharp
        /// <summary>
        /// Retrieve the UUID given a username
        /// This one is no longer used during auth since the new method get the UUID
        /// </summary>
        public static Guid GetUUID(string username)
        {
            using (WebClient client = new WebClient())
            {
                /*
            'header'  => "Content-type: application/json\r\n",
            'method'  => 'POST',
            'content' => '{"name":"'.$username.'","agent":"minecraft"}',

                context  = stream_context_create(options);
                result = file_get_contents(url, false, $context);
                return res;
                */

                var request = new Request();
                request.name = username;

                byte[] req = Json.Serialize(request);

                // Download data.
                byte[] resp = client.UploadData(url, req);
                var response = Json.Deserialize<Response>(resp);

                if(response.profiles.Count == 0)
                    throw new InvalidOperationException("Bad response: " + Encoding.UTF8.GetString(resp));
                Guid id = response.profiles[0].id;
                if (id == Guid.Empty)
                    throw new InvalidOperationException("Bad response: " + Encoding.UTF8.GetString(resp));
                return id;
            }
        }
コード例 #6
0
ファイル: Live.cs プロジェクト: bfhhq/csharp-sdk
        public static void DeleteChannel(String token)
        {
            try {

                String json = "{\"token\":\"" + token + "\"}";

                var client = new System.Net.WebClient();
                client.Headers.Add("Content-Type", "application/json");
                var resp = client.UploadData(Const.LiveDeleteUrl, "POST",
                            System.Text.Encoding.UTF8.GetBytes(json));

                var respStr = System.Text.Encoding.UTF8.GetString(resp);

                var result = SimpleJsonParser.Parse(respStr); ;

                int status = 99;

                if (result.ContainsKey("status")) {
                    status = int.Parse(result["status"]);
                    if (status == 0) {
                        return;
                    }
                }

                throw new CloudException(status, "");

            } catch (WebException e) {
                throw new CloudException(99, e.ToString());
            }
        }
コード例 #7
0
ファイル: Malwares.aspx.cs プロジェクト: pande88/votchina
        protected void FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
        {
            if (e.UploadedFile.FileName != String.Empty)
            {
                e.CallbackData = e.UploadedFile.FileName;

                try
                {
                    String ftpAddres = "ftp://" + _settings.RemoteHost + "/" + e.UploadedFile.FileName;

                    MLogger.LogTo(Level.TRACE, false, "Loading file " + e.UploadedFile.FileName + " to " + ftpAddres);

                    using (var webClient = new WebClient())
                    {
                        webClient.UploadData(new Uri(ftpAddres), e.UploadedFile.FileBytes);
                    }

                    MlwrManager.AddMlwr("default", e.UploadedFile.FileName, _userId);
                    UpdateTableView();
                }
                catch (Exception ex)
                {
                    MLogger.LogTo(Level.ERROR, false, "Exception during loading: " + ex.Message);

                    //test!!!
                    //MlwrManager.AddMlwr("default", e.UploadedFile.FileName, _userId);
                    //UpdateTableView();
                }
            }
        }
コード例 #8
0
 public string[] GetFirstLevelDepartmentIdByDepartment(int departmentId)
 {
     string postString = string.Join("&", "url=http://service.dianping.com/ba/base/organizationalstructure/OrganizationService_1.0.0"
                                         , "method=getDepartmentHierarchy"
                                         , "parameterTypes=int"
                                         , "parameters=" + departmentId.ToString());
     byte[] postData = Encoding.UTF8.GetBytes(postString);
     List<Department> departmentList = new List<Department>();
     using (WebClient client = new WebClient())
     {
         client.Headers.Add("serialize", 7.ToString());
         client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
         byte[] responseData = client.UploadData(ORGANIZATIONAL_STRUCTURE_PIGEON, "POST", postData);//得到返回字符流
         string result = Encoding.UTF8.GetString(responseData);//解码
         departmentList = JsonConvert.DeserializeObject<List<Department>>(result);
     }
     if (departmentList == null)
     {
         return new List<string>().ToArray();
     }
     else
     {
         var firstLevelDepartment = departmentList.SingleOrDefault(_ => _.Level == 1);
         if (firstLevelDepartment == null)
         {
             return new List<string>().ToArray();
         }
         else
         {
             return new string[] { firstLevelDepartment.DepartmentId.ToString() };
         }
     }
 }
コード例 #9
0
        public static bool enrollStuentInClass(string user_ref, string class_ref, string onBehalfOf)
        {
            WebClient restClient = new WebClient();
            restClient.Headers.Add("Content-Type", Global.ASSITments_ContentType);

            String AuthOnBehalf = "partner=" + "\"" + "Hien-Ref" + "\",onBehalfOf=" + "\"" + onBehalfOf + "\"";
            restClient.Headers.Add("assistments-auth", AuthOnBehalf);

            string enrollStudentClass = String.Format("{0}/class_membership", Global.ASSITmentsBaseAPI);

            string postData = "{" + "\"" + "user" + "\"" + ":" + "\"" + user_ref + "\"" + "," +
                                    "\"" + "class" + "\"" + ":" + "\"" + class_ref + "\"" + "}";
            byte[] byteResult = new byte[]{};
            byte[] byteArray = Encoding.ASCII.GetBytes(postData);
            try
            {
                byteResult = restClient.UploadData(enrollStudentClass, "POST", byteArray);
            }
            catch (Exception e)
            {
                return false;
            }
            string retStr = Encoding.ASCII.GetString(byteResult);
            return true;
        }
コード例 #10
0
ファイル: InfoRunner.cs プロジェクト: apcros/HubbleWin
        public void run()
        {
            ApiEngine ae      = new ApiEngine(conf);
            Boolean   verbose = conf.getCfg("verbose").Equals("yes");

            while (true)
            {
                Console.Clear();
                string json_to_submit = ae.getJson();
                using (var client = new System.Net.WebClient())
                {
                    try
                    {
                        client.Headers[HttpRequestHeader.ContentType] = "application/json";
                        client.Headers.Add("HUBBLE-DEVICE-KEY", conf.getCfg("device_key"));
                        client.UploadData(conf.getCfg("apiEntry") + "api/v1/devices/" + conf.getCfg("device_id") + "/latest", System.Text.Encoding.UTF8.GetBytes(json_to_submit));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.StackTrace);
                    }
                }

                if (verbose)
                {
                    Console.WriteLine("Following JSON was sent for " + conf.getCfg("device_id") + "\n");
                    Console.WriteLine(json_to_submit);
                }

                System.Threading.Thread.Sleep(int.Parse(conf.getCfg("refreshTime")));
            }
        }
コード例 #11
0
ファイル: CaptureCommand.cs プロジェクト: pix3lot/Slackit
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            string TempPath = Path.GetTempPath();
            System.Drawing.Rectangle bounds = Screen.GetBounds(System.Drawing.Point.Empty);
            using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
            {
                using (Graphics g = Graphics.FromImage(bitmap))
                {
                    g.CopyFromScreen(System.Drawing.Point.Empty, System.Drawing.Point.Empty, bounds.Size);
                }
                bitmap.Save(TempPath + "SlackitCapture.jpg", ImageFormat.Jpeg);
            }

            FileStream str = File.OpenRead(TempPath + "SlackitCapture.jpg");
            byte[] fBytes = new byte[str.Length];
            str.Read(fBytes, 0, fBytes.Length);
            str.Close();

            var webClient = new WebClient();
            string boundary = "------------------------" + DateTime.Now.Ticks.ToString("x");
            webClient.Headers.Add("Content-Type", "multipart/form-data; boundary=" + boundary);
            var fileData = webClient.Encoding.GetString(fBytes);
            var package = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n{3}\r\n--{0}--\r\n", boundary, "Slackit Capture", "multipart/form-data", fileData);

            var nfile = webClient.Encoding.GetBytes(package);
            string url = "https://slack.com/api/files.upload?token=" + Variables.slackToken + "&content=" + nfile + "&channels=" + Variables.slackChId;

            byte[] resp = webClient.UploadData(url, "POST", nfile);

            var k = System.Text.Encoding.Default.GetString(resp);
            //Console.WriteLine(k);
            //Console.ReadKey();

            return Result.Succeeded;
        }
コード例 #12
0
ファイル: Gist.cs プロジェクト: masaru-b-cl/GistSharp
 protected virtual string PostGists(WebClient client, string dataRaw)
 {
     var data = encoding.GetBytes(dataRaw);
       var responseRaw = client.UploadData(@"https://api.github.com/gists", data);
       var json = encoding.GetString(responseRaw);
       return json;
 }
コード例 #13
0
 public static void PutRequestToBridge(string fullUri, string data, string contentType = "application/json", string method = "PUT")
 {
     using (var client = new System.Net.WebClient())
     {
         client.UploadData(fullUri, method, Encoding.UTF8.GetBytes(data));
     }
 }
コード例 #14
0
ファイル: Upload.cs プロジェクト: GSBCfamily/bvcms
        public void UploadExcelFromSqlToDropBox(string savedQuery, string sqlscript, string targetpath, string filename)
        {
            using (var db2 = NewDataContext())
            {
                var accesstoken = db2.Setting("DropBoxAccessToken", ConfigurationManager.AppSettings["DropBoxAccessToken"]);
                var script = db2.Content(sqlscript, "");
                if (!script.HasValue())
                    throw new Exception("no sql script found");

                var p = new DynamicParameters();
                foreach (var kv in dictionary)
                    p.Add("@" + kv.Key, kv.Value);
                if (script.Contains("@qtagid"))
                {
                    int? qtagid = null;
                    if (savedQuery.HasValue())
                    {
                        var q = db2.PeopleQuery2(savedQuery);
                        var tag = db2.PopulateSpecialTag(q, DbUtil.TagTypeId_Query);
                        qtagid = tag.Id;
                    }
                    p.Add("@qtagid", qtagid);
                }
                var bytes = db2.Connection.ExecuteReader(script, p).ToExcelBytes(filename);

                var wc = new WebClient();
                wc.Headers.Add($"Authorization: Bearer {accesstoken}");
                wc.Headers.Add("Content-Type: application/octet-stream");
                wc.Headers.Add($@"Dropbox-API-Arg: {{""path"":""{targetpath}/{filename}"",""mode"":""overwrite""}}");
                wc.UploadData("https://content.dropboxapi.com/2-beta-2/files/upload", bytes);
            }
        }
コード例 #15
0
ファイル: Factory.cs プロジェクト: wyerp/.NET-sdk
        private string Ajax(string url, byte[] data, string method)
        {
            try
            {
                WebClient webClient = new WebClient();
                foreach (var header in headers)
                {
                    webClient.Headers.Add(header.Key, header.Value);
                }
                string ResponseData;
                if (data != null)
                {
                    var responseData = webClient.UploadData(url, method, data);
                    ResponseData = System.Text.Encoding.GetEncoding("UTF-8").GetString(responseData);
                }
                else
                {
                    ResponseData = webClient.DownloadString(url);
                }

                return ResponseData;
            }
            catch (WebException e)
            {
                return "{ \"Error\":{ \"msg\": \"" + e.Message + "\"}}";
            }
        }
コード例 #16
0
ファイル: Push.cs プロジェクト: wyerp/.NET-sdk
        private string Ajax(string url, byte[] data, string method)
        {
            try
            {
                WebClient webClient = new WebClient();
                webClient.Headers.Add("X-APICloud-AppId", AppId);
                webClient.Headers.Add("X-APICloud-AppKey", X_APICloud_AppKey);
                webClient.Headers.Add("Content-type", "application/json;charset=UTF-8");
                string ResponseData;
                if (data != null)
                {
                    var responseData = webClient.UploadData(url, method, data);
                    ResponseData = System.Text.Encoding.GetEncoding("UTF-8").GetString(responseData);
                }
                else
                {
                    ResponseData = webClient.DownloadString(url);
                }

                return ResponseData;
            }
            catch (WebException e)
            {
                return "{ \"Error\":{ \"msg\": \"" + e.Message + "\"}}";
            }
        }
コード例 #17
0
ファイル: Upload.cs プロジェクト: bfhhq/csharp-sdk
        public static String RequestUploadUrl(String json)
        {
            var client = new System.Net.WebClient();
            client.Headers.Add("Content-Type", "application/json");
            var resp = client.UploadData(Const.UploadRequestUrl, "POST",
                System.Text.Encoding.UTF8.GetBytes(json));

            var respStr = System.Text.Encoding.UTF8.GetString(resp);

            var result = SimpleJsonParser.Parse(respStr); ;

            int status = 99;
            String errMsg = "";

            if (result.ContainsKey("status")) {
            status = int.Parse(result["status"]);
            if (status == 0) {
            return result["url"];
            }
            }

            if (result.ContainsKey("errmsg")) {
            errMsg = result["errmsg"];
            }

            throw new CloudException(status, errMsg);
        }
コード例 #18
0
        private Task<string> UploadBytesAsync(string method, IProgress<string> progress)
        {
            return Task.Run(() =>
                {
                    using (var client = new WebClient())
                    {
                        var address = restClient.PrepareUri();

                        restClient.SetHeaders(client);
                        
                        client.TraceRequest(address, method, progress);

                        var watch = new Stopwatch();
                        watch.Start();
                        client.UploadData(address, method, content);
                        watch.Stop();

                        client.TraceResponse(address,
                                                  method,
                                                  string.Format(CultureInfo.InvariantCulture,
                                                                "Completed in {0} seconds",
                                                                watch.Elapsed.TotalSeconds),
                                                  progress);
                    }

                    return "Done";
                });
        }
コード例 #19
0
        public void EditCard(object sender, GridViewUpdateEventArgs e)
        {
            Card Card = new Card();

            Card.VerbatimDeckId = Int32.Parse(HiddenDeckId.Value.ToString());
            Card.VerbatimCardId = Int32.Parse(e.NewValues["VerbatimCardId"].ToString());
            Card.Title          = e.NewValues["Title"].ToString();
            if (e.NewValues["Description"] != null)
            {
                Card.Description = e.NewValues["Description"].ToString();
            }
            Card.Category   = e.NewValues["Category"].ToString();
            Card.PointValue = Int32.Parse(e.NewValues["PointValue"].ToString());
            if (e.NewValues["PictureURL"] != null)
            {
                Card.PictureURL = e.NewValues["PictureURL"].ToString();
            }


            string QueryURL = Utilities.ServerDNS + "/EditCard";

            using (var client = new System.Net.WebClient())
            {
                client.UploadData(QueryURL, "PUT", Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(Card)));
            }
        }
コード例 #20
0
ファイル: HttpTests.cs プロジェクト: sq/Fracture
        public void AcceptedRequestOffersBody()
        {
            Server.EndPoints.Add(ListenPort);
            Scheduler.WaitFor(Server.StartListening());

            var dataToUpload = new byte[1024 * 1024];
            for (var i = 0; i < dataToUpload.Length; i++)
                dataToUpload[i] = (byte)(i % 256);

            using (var wc = new WebClient()) {
                var fPost = Future.RunInThread(
                    () => {
                        var result = wc.UploadData(ServerUri, dataToUpload);
                        Console.WriteLine("Upload complete");
                        return result;
                    }
                );

                var request = Scheduler.WaitFor(Server.AcceptRequest(), 3);
                Console.WriteLine(request);

                Assert.AreEqual("POST", request.Line.Method);
                Assert.AreEqual("localhost", request.Line.Uri.Host);
                Assert.AreEqual("/", request.Line.Uri.AbsolutePath);

                var requestBody = Scheduler.WaitFor(request.Body.Bytes);
                Assert.AreEqual(dataToUpload.Length, requestBody.Length);
                Assert.AreEqual(dataToUpload, requestBody);

                request.Dispose();

                Scheduler.WaitFor(fPost, WebClientTimeout);
            }
        }
コード例 #21
0
ファイル: LoadMalware.aspx.cs プロジェクト: alexkasp/monitor
        protected void FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
        {
            if (e.UploadedFile.FileName != String.Empty)
            {
                e.CallbackData = e.UploadedFile.FileName;

                try
                {
                    var settings = ConnectionManager.LoadSettings();
                    String ftpAddres = "ftp://" + settings.RemoteHost + "/" + e.UploadedFile.FileName;

                    MLogger.LogTo(Level.TRACE, false, "Uploading file " + e.UploadedFile.FileName + " to " + ftpAddres);

                    using (var webClient = new WebClient())
                    {
                        webClient.UploadData(new Uri(ftpAddres), e.UploadedFile.FileBytes);
                    }

                    MlwrManager.AddMlwr("default", e.UploadedFile.FileName, UserId, "","","");
                    MLogger.LogTo(Level.TRACE, false, "Add malware '" + e.UploadedFile.FileName + "' by user '" + UserManager.GetUser(UserId).UserName + "'");
                }
                catch (Exception ex)
                {
                    MLogger.LogTo(Level.ERROR, false, "Exception during uploading: " + ex.Message);
                }
            }
            Response.Redirect("~/Pages/Information/MalwareInfo.aspx");
        }
コード例 #22
0
ファイル: UploadService.cs プロジェクト: ssrahul96/HNA
        public void upload(string mtime, string mdate, string message, string path)
        {
            temp = new JObject();

            string address = "https://hna-test.firebaseio.com/" + mdate + "/" + mtime + ".json";

            Mdata md = new Mdata();

            md.mdate    = mdate;
            md.mtime    = mtime;
            md.mmessage = message;
            md.mpath    = path;

            //temp.Add("mdate", mdate);
            //temp.Add("mtime", mtime);
            //temp.Add("message", message);
            //temp.Add("path", path);


            string data = JsonConvert.SerializeObject(md);

            Debug.WriteLine("\n" + md);
            using (var client = new System.Net.WebClient())
            {
                client.UploadData(address, "PUT", Encoding.ASCII.GetBytes(data));
            }
        }
コード例 #23
0
        public override string Translate(string text, ref string from)
        {
            string transText = "";
            string transURL = "http://www.freetranslation.com/gw-mt-proxy-service-web/mt-translation";

            try
            {

                using (WebClient client = new WebClient())
                {

                    NameValueCollection headers = new NameValueCollection()
                    {
                        { "Content-Type", "application/json; charset=UTF-8" },
                        { "Tracking", "applicationKey=dlWbNAC2iLJWujbcIHiNMQ%3D%3D applicationInstance=freetranslation" }   // Public translarion service
                    };
                    client.Headers.Add(headers);

                    JObject postData = new JObject();
                    postData["text"] = HttpUtility.UrlEncode(text);
                    postData["from"] = from;
                    postData["to"] = "eng";

                    byte[] b_transResp = client.UploadData(transURL, Encoding.UTF8.GetBytes(postData.ToString()));
                    string transResp = Encoding.UTF8.GetString(b_transResp);
                    JObject trObject = JObject.Parse(transResp);
                    transText = trObject["translation"].ToString().TrimStart();

                }

            }
            catch (Exception e) { transText = text; from = "ERROR"; }

            return transText.Length > 0 ? transText : text;
        }
コード例 #24
0
ファイル: Comm.cs プロジェクト: eatage/AppTest.bak
        public static string of_SendPost(string Url, string Params)
        {
            if (GYstring.of_LeftStr(Url, 7).ToLower() != "http://")
            {
                Url = "http://" + Url;
            }

            //初始化WebClient 
            System.Net.WebClient webClient = new System.Net.WebClient();
            webClient.Headers.Add("Accept", "*/*");
            webClient.Headers.Add("Accept-Language", "zh-cn");
            webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            webClient.Headers.Add(HttpRequestHeader.KeepAlive, "FALSE");

            //将字符串转换成字节数组  
            string srcString;
            byte[] postData = Encoding.GetEncoding("GB2312").GetBytes(Params);
            try
            {
                byte[] responseData = webClient.UploadData(Url, "POST", postData);
                srcString = Encoding.GetEncoding("GB2312").GetString(responseData);

                srcString = GYstring.of_trim(srcString);
            }
            catch (Exception Exce)
            {
                return Exce.ToString();
            }
            return srcString;
        }
コード例 #25
0
ファイル: TestVaultUtils.cs プロジェクト: inorton/testvault
        public static void SubmitResult(Uri testVaultServer, string session, string project, string buildname, string testgroup, string testname, TestOutcome outcome, bool personal)
        {
            try
            {
                using ( var client = new WebClient() ){

                    client.BaseAddress = testVaultServer.ToString();
                    client.CachePolicy = new System.Net.Cache.RequestCachePolicy( System.Net.Cache.RequestCacheLevel.NoCacheNoStore );
                    client.Headers.Add("Content-Type", "text/xml");

                    var result = new TestResult()
                    {
                        Group = new TestGroup() { Name = testgroup, Project = new TestProject() { Project = project } },
                        Name = testname,
                        Outcome = outcome,
                        TestSession = session,
                        IsPersonal = personal,
                        BuildID = buildname,
                    };

                    var xc = new XmlSerializer(result.GetType());
                    var io = new System.IO.MemoryStream();
                    xc.Serialize( io, result );

                    client.UploadData( testVaultServer.ToString(), io.ToArray() );

                }
            } catch ( Exception e )
            {
                Console.Error.WriteLine( e );
            }
        }
コード例 #26
0
ファイル: MainForm.cs プロジェクト: Flard/ArduinoCosmLogger
 public static void PostValue(string value)
 {
     byte[] postArray = Encoding.ASCII.GetBytes(value);
     WebClient wc = new WebClient();
     wc.Headers.Add("X-PachubeApiKey", _apiKey);
     wc.UploadData("http://www.pachube.com/api/" + _listId + ".csv", "PUT", postArray);
 }
コード例 #27
0
ファイル: Topics.cs プロジェクト: MudaKaizen/HackishAzure
 /// <summary>
 /// Deletes a topic by name.
 /// </summary>
 /// <param name="topicName">The name of the topic to delete.</param>
 /// <returns>true | false</returns>
 public bool Delete(string topicName)
 {
     try
     {
         byte[] resp = null;
         using (WebClient wc = new WebClient())
         {
             wc.Headers[HttpRequestHeader.Authorization] = _authToken.Token;
             string uri = Topics.URI_Delete
                 .Replace("{serviceNamespace}", _authToken.ServiceNamespace)
                 .Replace("{Topic Path}", topicName);
             resp = wc.UploadData(uri, HttpMethods.DELETE, new byte[0]);
         }
         if (resp != null)
         {
             return true;
         }
         else
         {
             return false;
         }
     }
     catch (WebException wex)
     {
         throw wex;
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
コード例 #28
0
ファイル: YACHelper.cs プロジェクト: yacwechat/wechatv1
 public static string SetYACCancelUserOpenId(string openId, int channel)
 {
     string returnCode = "0";
     try
     {
         WebClient wc = new WebClient();
         StringBuilder postData = new StringBuilder();
         postData.Append("[{\"openid\":\"");
         postData.Append(openId);
         postData.Append("\",");
         postData.Append("\"channel_code\":\"");
         postData.Append("weixinqrcode_" + channel);
         postData.Append("\",");
         postData.Append("\"fans_cancel_time\":\"");
         postData.Append(DateTime.Now.ToString("“yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'”"));
         postData.Append("\"");
         postData.Append("}]");
         byte[] recdata = null;
         byte[] sendData = Encoding.UTF8.GetBytes(postData.ToString());
         wc.Headers.Add("Content-Type", "application/json;charset=UTF-8");
         wc.Headers.Add("ContentLength", sendData.Length.ToString());
         recdata = wc.UploadData(WeChatWebAPI.SetCannelYACUserToken, "POST", sendData);
         if (recdata != null)
         {
             //var jsonModel = (JObject)JsonConvert.DeserializeObject(Encoding.UTF8.GetString(recdata));
             //returnCode = "code:" + jsonModel.SelectToken("code").ToString() + ";" + "data" + jsonModel.SelectToken("data").ToString();
         }
     }
     catch
     { }
     return returnCode;
 }
        /// <summary>
        /// This method is used to upload a file to the specified URI.
        /// </summary>
        /// <param name="fileUrl">Specify the URL where the file will be uploaded to.</param>
        /// <param name="fileName">Specify the name for the file to upload.</param>
        /// <returns>Return true if the operation succeeds, otherwise return false.</returns>
        public bool UploadTextFile(string fileUrl, string fileName)
        {
            WebClient client = new WebClient();
            string fullFileUri = string.Format("{0}/{1}", fileUrl, fileName);
            try
            {
                byte[] contents = System.Text.Encoding.UTF8.GetBytes(Common.Common.GenerateResourceName(Site, "FileContent"));
                client.Credentials = new NetworkCredential(Common.Common.GetConfigurationPropertyValue("UserName1", Site), Common.Common.GetConfigurationPropertyValue("Password1", Site), Common.Common.GetConfigurationPropertyValue("Domain", Site));

                if (fullFileUri.StartsWith("HTTPS", System.StringComparison.OrdinalIgnoreCase))
                {
                    Common.Common.AcceptServerCertificate();
                }

                client.UploadData(fullFileUri, "PUT", contents);
            }
            catch (System.Net.WebException ex)
            {
                Site.Log.Add(
                    LogEntryKind.Debug,
                    string.Format("Cannot upload the file to the full URI {0}, the exception message is {1}", fullFileUri, ex.Message));

                return false;
            }
            finally
            {
                if (client != null)
                {
                    client.Dispose();
                }
            }

            return true;
        }
コード例 #30
0
        private string SendSms(string token, string recipientNumber, string message)
        {
            try
            {
                using (var webClient = new System.Net.WebClient())
                {
                    webClient.Headers.Clear();
                    webClient.Headers.Add(HttpRequestHeader.ContentType, @"application/json");
                    webClient.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + token);

                    string data           = "{\"to\":\"" + recipientNumber + "\", \"body\":\"" + message + "\"}";
                    var    response       = webClient.UploadData("https://api.telstra.com/v1/sms/messages", "POST", Encoding.Default.GetBytes(data));
                    var    responseString = Encoding.Default.GetString(response);
                    var    obj            = JObject.Parse(responseString);
                    return(obj.GetValue("messageId").ToString());

                    // Now parse with JSON.Net
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return(string.Empty);
        }
コード例 #31
0
    /// <summary>
    /// analys image
    /// </summary>
    /// <param name="imageFilePath"></param>
    void MakeAnalysisRequest(string imageFilePath)
    {
        FaceApi.Module.Base   BaseApi   = new FaceApi.Module.Base();
        FaceApi.Module.Detect DetectApi = new FaceApi.Module.Detect();
        using (System.Net.WebClient wc = new System.Net.WebClient()) {
            wc.Headers.Add("Ocp-Apim-Subscription-Key", FaceApi.Module.Base.subscriptionKey);
            wc.Headers.Add("Content-Type", "application/octet-stream");

            // Request parameters. A third optional parameter is "details".
            string requestParameters = "returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise";

            // Assemble the URI for the REST API Call.
            string uri = FaceApi.Module.Detect.uriBase + "?" + requestParameters;

            byte[] byteData = BaseApi.GetImageAsByteArray(imageFilePath);

            byte[] result = wc.UploadData(uri, "POST", byteData);
            String s      = System.Text.Encoding.UTF8.GetString(result, 0, result.Length);
            Response.Write(s + "<br />");
            List <FaceApi.Infos.Face> resultFace = Newtonsoft.Json.JsonConvert.DeserializeObject <List <FaceApi.Infos.Face> >(s);
            Response.Write("人數:" + resultFace.Count + "<br />");

            foreach (FaceApi.Infos.Face human in resultFace)
            {
                Response.Write("   age:" + human.faceAttributes.age + ", sex:" + human.faceAttributes.gender + "<br />");
            }
        }
    }
コード例 #32
0
        public static string CreateUser(string user_token, string firstname, string lastname,string password, string username)
        {
            WebClient restClient = new WebClient();
            restClient.Headers.Add("Content-Type", Global.ASSITments_ContentType);
            restClient.Headers.Add("assistments-auth", Global.ASSITments_Auth_WOBehalf);
            string createUserURL = String.Format("{0}/user", Global.ASSITmentsBaseAPI);

            string postData = "{" + "\"" + "userType" + "\"" + ":" + "\"" + "proxy" + "\"" + "," +
                                    "\"" + "username" + "\"" + ":" + "\"" + username + "\"" + "," +
                                    "\"" + "password" + "\"" + ":" + "\"" + password + "\"" + "," +
                                    "\"" + "email" + "\"" + ":" + "\"" + "4" + firstname + lastname + "@junk.com" + "\"" + "," +
                                    "\"" + "firstName" + "\"" + ":" + "\"" + firstname + "\"" + "," +
                                    "\"" + "lastName" + "\"" + ":" + "\"" + lastname + "\"" + "," +
                                    "\"" + "displayName" + "\"" + ":" + "\"" + "4" + firstname + " " + lastname + "\"" + "," +
                                    "\"" + "timeZone" + "\"" + ":" + "\"" + "GMT-4" + "\"" + "," +
                                    "\"" + "registrationCode" + "\"" + ":" + "\"" + "HIEN-API" + "\"" + "}";
            byte[] byteArray = Encoding.ASCII.GetBytes(postData);
            byte[] byteResult = restClient.UploadData(createUserURL, "POST", byteArray);
            string retStr = Encoding.ASCII.GetString(byteResult);

            JObject response = JObject.Parse(retStr);
            string student_ref = response["user"].ToString();

            return student_ref;
        }
コード例 #33
0
        public static void DeleteFile(String token)
        {
            try {
                String json = "{\"token\":\"" + token + "\"}";

                var client = new System.Net.WebClient();
                client.Headers.Add("Content-Type", "application/json");
                var resp = client.UploadData(Const.DeleteRequestUrl, "POST",
                                             System.Text.Encoding.UTF8.GetBytes(json));

                var respStr = System.Text.Encoding.UTF8.GetString(resp);

                var result = SimpleJsonParser.Parse(respStr);;

                int status = 99;

                if (result.ContainsKey("status"))
                {
                    status = int.Parse(result["status"]);
                    if (status == 0)
                    {
                        return;
                    }
                }

                throw new CloudException(status, "");
            } catch (WebException e) {
                throw new CloudException(99, e.ToString());
            }
        }
コード例 #34
0
ファイル: Default.aspx.cs プロジェクト: kevindwf/SendToKindle
        private string GetWebContent(string url, string postData)
        {
            var webClient = new WebClient();
            var result = webClient.UploadData(url, Encoding.GetEncoding("utf-8").GetBytes(postData));

            return Encoding.GetEncoding("utf-8").GetString(result);
        }
コード例 #35
0
        public void HttpUploadFile2()
        {
            string       fileName = "E:\\1_ycxjex2006.jpg";                                   //E:\\案例.rar
            string       url      = "http://localhost:50887/API/FxtMobileAPI.svc/UpLoadFileSeries";
            long         cruuent  = HttpGetFile(fileName);                                    //获取服务器已经上传的大小
            FileStream   fStream  = new FileStream(fileName, FileMode.Open, FileAccess.Read); //将文件加载到文件流
            BinaryReader bReader  = new BinaryReader(fStream);                                //将文件了加载成二进制数据
            long         length   = fStream.Length;                                           //当前文件的总大小

            fileName = fileName.Substring(fileName.LastIndexOf('\\') + 1);                    //获取文件名称
            //如果服务器已经有过此文件
            if (cruuent > 0)
            {
                //将文件流的读取位置移到服务器已上传的大小的位置
                fStream.Seek(cruuent, SeekOrigin.Current);
            }
            //创建一个用于存储要上传文件内容的字节对象
            byte[] data = new byte[length - cruuent];
            //将流中读取指定字节数加载到到字节对象data
            bReader.Read(data, 0, Convert.ToInt32(length - cruuent));
            url = url + "?filename=" + fileName + "&npos=" + cruuent;
            WebClient webClientObj = new System.Net.WebClient();

            webClientObj.Headers.Add("Content-Type", "application/octet-stream");
            byte[] result = webClientObj.UploadData(url, "POST", data);
            string ll     = Encoding.Default.GetString(result);
            //"E:\\案例.rar"
        }
コード例 #36
0
 public void RunAsync()
 {
   var ctx = System.Threading.SynchronizationContext.Current;
   System.Threading.ThreadPool.QueueUserWorkItem(state => {
     var client = new WebClient();
     var rand   = new Random();
     var data   = new byte[DataSize];
     rand.NextBytes(data);
     var results = new BandwidthCheckResult[Tries];
     for (var i=0; i<Tries; i++) {
       try {
         var stopwatch = new System.Diagnostics.Stopwatch();
         stopwatch.Start();
         var response_body = client.UploadData(Target, data);
         stopwatch.Stop();
         results[i].ElapsedTime = stopwatch.Elapsed;
         results[i].Succeeded = true;
       }
       catch (WebException) {
         results[i].Succeeded = false;
       }
     }
     if (BandwidthCheckCompleted!=null) {
       var success = results.Count(r => r.Succeeded)>0;
       var average_seconds = results.Average(r => r.ElapsedTime.TotalSeconds);
       ctx.Post(s => {
         BandwidthCheckCompleted(
           this,
           new BandwidthCheckCompletedEventArgs(success, DataSize, TimeSpan.FromSeconds(average_seconds)));
       }, null);
     }
   });
 }
コード例 #37
0
 public void SendPut(string address, byte[] data)
 {
     using (var client = new System.Net.WebClient())
     {
         client.UploadData(address, "PUT", data); // From string: Encoding.ASCII.GetBytes(putData)
     }
 }
コード例 #38
0
        public String PutObject(string postUrl, XmlDocument xmlDoc)
        {
            NetworkCredential myCreds = new NetworkCredential(_username, _password);

            MemoryStream xmlStream = new MemoryStream();

            xmlDoc.Save(xmlStream);

            string result = "";

            xmlStream.Flush();
            //Adjust this if you want read your data
            xmlStream.Position = 0;

            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                client.Credentials = myCreds;
                client.Headers.Add("Content-Type", "application/xml");
                byte[] b = client.UploadData(postUrl, "PUT", xmlStream.ToArray());
                //Dim b As Byte() = client.UploadFile(postUrl, "PUT", "C:\test\test.xml")

                result = client.Encoding.GetString(b);
            }

            return(result);
        }
コード例 #39
0
        protected void Page_Load(object sender, EventArgs e)
        {
            bool bSuccess = false;
            string secret = Request.QueryString["x"];
            string uap_token = Request.QueryString["uap_token"];
            string uap_username = Request.QueryString["uap_username"];
            string uap_module = Request.QueryString["uap_module"];

            try
            {
                if (secret == "x")
                {
                    bSuccess = true;
                    uap_username = "******";
                }
                else if (string.IsNullOrEmpty(uap_token) || string.IsNullOrEmpty(uap_username) || string.IsNullOrEmpty(uap_module))
                {
                    bSuccess = false;
                }
                else
                {
                    WebClient wc = new WebClient();
                    JObject pObj = new JObject();
                    pObj.Add("token", uap_token);
                    pObj.Add("username", uap_username);
                    string sData = pObj.ToString();
                    wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                    wc.Headers.Add("ContentLength", sData.Length.ToString());

                    byte[] pData = Encoding.UTF8.GetBytes(sData);
                    string pUrl = ConfigurationManager.AppSettings["validate"];
                    byte[] rData = wc.UploadData(string.Format("{0}?token={1}&username={2}", pUrl, uap_token, uap_username), "POST", pData);
                    //byte[] rData = wc.UploadData(string.Format("http://188.166.252.54:8080/validate_token?token={1}&username={2}", pUrl, uap_token, uap_username), "POST", pData);
                    string sReturn = Encoding.UTF8.GetString(rData);
                    JObject rObj = JObject.Parse(sReturn);
                    bSuccess = rObj.Value<int>("code") == 0 ? true : false;
                }
            }
            catch (System.Exception ex)
            {
                bSuccess = false;
            }
            finally
            {
                if (bSuccess)
                {
                    this.Session["username"] = uap_username;
                    this.Response.Redirect("PlatformMap.aspx");
                }
                else
                {
                    this.Session["username"] = null;
                    //ClientScript.RegisterStartupScript(Page.GetType(), "", "<script language=javascript>window.opener=null;window.open('','_self');window.close();</script>");
                    //Response.Write("<script language=javascript>window.opener=null;window.open('','_self');window.close();</script>");
                    string sLoginPage = ConfigurationManager.AppSettings["loginpage"];
                    this.Response.Redirect(sLoginPage);
                }
            }
        }
コード例 #40
0
ファイル: StopDetails.cs プロジェクト: aditya-gune/MobileApp1
        private void saveHomeClick(object sender, EventArgs e)
        {
            string entity    = MainActivity.currentUser + "_stops";
            var    userstops = db.GetDocument(entity);

            if (userstops.GetProperty("homeid") == null)
            {
                userstops.Update((UnsavedRevision newRevision) =>
                {
                    var properties         = newRevision.Properties;
                    properties["homeid"]   = stopid;
                    properties["homename"] = stopname;
                    return(true);
                });
                string     url     = "http://10.0.0.94:4985/couchbaseevents";
                WebRequest request = WebRequest.Create(url);
                request.Method = "DELETE";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                savehome.Text = "Unsave";
            }
            else if (userstops.GetProperty("homeid").ToString() == stopid)
            {
                savehome = FindViewById <Button>(Resource.Id.saveHome);
                userstops.Update((UnsavedRevision newRevision) =>
                {
                    var properties         = newRevision.Properties;
                    properties["homeid"]   = "";
                    properties["homename"] = "";
                    return(true);
                });
                string url = "http://10.0.0.94:4985/couchbaseevents";
                byte[] nullbyte;
                var    data = new Dictionary <string, object> {
                    { "username", null },
                    { "password", null }
                };
                var binFormatter = new BinaryFormatter();
                var mStream      = new MemoryStream();
                binFormatter.Serialize(mStream, data);

                using (var client = new System.Net.WebClient())
                {
                    client.UploadData(url, "PUT", mStream.ToArray());
                }
                savehome.Text = "Save as Home";
            }
            else
            {
                userstops.Update((UnsavedRevision newRevision) =>
                {
                    var properties         = newRevision.Properties;
                    properties["homeid"]   = stopid;
                    properties["homename"] = stopname;
                    return(true);
                });
                savehome.Text = "Unsave";
            }
        }
コード例 #41
0
        public void RSPEC_WebClient(string address, Uri uriAddress, byte[] data,
                                    NameValueCollection values)
        {
            System.Net.WebClient webclient = new System.Net.WebClient();

            // All of the following are Questionable although there may be false positives if the URI scheme is "ftp" or "file"
            //webclient.Download * (...); // Any method starting with "Download"
            webclient.DownloadData(address);                            // Noncompliant
            webclient.DownloadDataAsync(uriAddress, new object());      // Noncompliant
            webclient.DownloadDataTaskAsync(uriAddress);                // Noncompliant
            webclient.DownloadFile(address, "filename");                // Noncompliant
            webclient.DownloadFileAsync(uriAddress, "filename");        // Noncompliant
            webclient.DownloadFileTaskAsync(address, "filename");       // Noncompliant
            webclient.DownloadString(uriAddress);                       // Noncompliant
            webclient.DownloadStringAsync(uriAddress, new object());    // Noncompliant
            webclient.DownloadStringTaskAsync(address);                 // Noncompliant

            // Should not raise for events
            webclient.DownloadDataCompleted   += Webclient_DownloadDataCompleted;
            webclient.DownloadFileCompleted   += Webclient_DownloadFileCompleted;
            webclient.DownloadProgressChanged -= Webclient_DownloadProgressChanged;
            webclient.DownloadStringCompleted -= Webclient_DownloadStringCompleted;


            //webclient.Open * (...); // Any method starting with "Open"
            webclient.OpenRead(address);
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^   {{Make sure that this http request is sent safely.}}
            webclient.OpenReadAsync(uriAddress, new object());              // Noncompliant
            webclient.OpenReadTaskAsync(address);                           // Noncompliant
            webclient.OpenWrite(address);                                   // Noncompliant
            webclient.OpenWriteAsync(uriAddress, "STOR", new object());     // Noncompliant
            webclient.OpenWriteTaskAsync(address, "POST");                  // Noncompliant

            webclient.OpenReadCompleted  += Webclient_OpenReadCompleted;
            webclient.OpenWriteCompleted += Webclient_OpenWriteCompleted;

            //webclient.Upload * (...); // Any method starting with "Upload"
            webclient.UploadData(address, data);                           // Noncompliant
            webclient.UploadDataAsync(uriAddress, "STOR", data);           // Noncompliant
            webclient.UploadDataTaskAsync(address, "POST", data);          // Noncompliant
            webclient.UploadFile(address, "filename");                     // Noncompliant
            webclient.UploadFileAsync(uriAddress, "filename");             // Noncompliant
            webclient.UploadFileTaskAsync(uriAddress, "POST", "filename"); // Noncompliant
            webclient.UploadString(uriAddress, "data");                    // Noncompliant
            webclient.UploadStringAsync(uriAddress, "data");               // Noncompliant
            webclient.UploadStringTaskAsync(uriAddress, "data");           // Noncompliant
            webclient.UploadValues(address, values);                       // Noncompliant
            webclient.UploadValuesAsync(uriAddress, values);               // Noncompliant
            webclient.UploadValuesTaskAsync(address, "POST", values);
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

            // Should not raise for events
            webclient.UploadDataCompleted   += Webclient_UploadDataCompleted;
            webclient.UploadFileCompleted   += Webclient_UploadFileCompleted;
            webclient.UploadProgressChanged -= Webclient_UploadProgressChanged;
            webclient.UploadStringCompleted -= Webclient_UploadStringCompleted;
            webclient.UploadValuesCompleted -= Webclient_UploadValuesCompleted;
        }
コード例 #42
0
        public FirebaseStreamParser(string route, string baseUrl)
        {
            toSend = new Queue <Dictionary <string, object> >();
            //  dataCache = new DataBranch();
            BaseUrl  = baseUrl;
            Added   += (k, e) => { };
            Changed += (k, e) => { };
            Deleted += (k, e) => { };

            Route         = route;
            receiveThread = new Thread(() =>
            {
                var client = new System.Net.WebClient();
                client.Headers.Add(System.Net.HttpRequestHeader.Accept, "text/event-stream");
                client.OpenReadCompleted += (s, e) =>
                {
                    using (StreamReader sr = new StreamReader(e.Result))
                    {
                        while (!sr.EndOfStream)
                        {
                            parse(sr.ReadLine());
                        }
                    }
                };
                client.OpenReadAsync(new Uri(baseUrl + route + ".json"));
            });
            receiveThread.IsBackground = true;
            receiveThread.Start();
            receiveThread.Name = ("FirebaseStreamParser -> " + route);
            sendThread         = new Thread(() =>
            {
                var client = new System.Net.WebClient();
                while (true)
                {
                    if (toSend.Count() != 0)
                    {
                        var uri = new Uri(baseUrl + route + ".json");
                        while (toSend.Count > 0)
                        {
                            var upd = toSend.Dequeue();
                            while (toSend.Count > 0 && tryJoin(upd, toSend.Peek()))
                            {
                                toSend.Dequeue();
                            }

                            //   var toUpdate = new DataBranch(upd.ToDictionary(entry => entry.Key, entry => (DataNode)new DataLeaf(entry.Value)));
                            //    dataCache.Merge(toUpdate);
                            client.UploadData(uri, "PATCH", Encoding.UTF8.GetBytes(serializeDictionary(upd)));
                        }
                    }

                    Thread.Sleep(10);
                }
            });
            sendThread.Name         = ("FirebaseStreamParser <- " + route);
            sendThread.IsBackground = true;
            sendThread.Start();
        }
コード例 #43
0
        } //end enum

        /// <summary>
        /// Make a web request via GET or POST
        /// </summary>
        /// <param name="MethodType"></param>
        /// <param name="szUrl"></param>
        /// <param name="headers"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        private string webRequest(Method MethodType, string szUrl, WebHeaderCollection headers, string data = null)
        {
            if (string.IsNullOrEmpty(szUrl))
                return null;

            WebRequest webrequest = WebRequest.Create(szUrl);

            if (MethodType == Method.Get)
            {
                webrequest.ContentType = "application/json";
                if (headers != null)
                {
                    webrequest.Headers = headers;
                }
            }
            string strResponse = null;
            try
            {
                if (MethodType == Method.Get)
                {
                    using (System.IO.Stream s = webrequest.GetResponse().GetResponseStream())
                    {
                        using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
                        {
                            strResponse = sr.ReadToEnd();
                            Console.WriteLine(String.Format("Response: {0}", strResponse));
                        }
                    }
                }
                if (MethodType == Method.Put)
                {
                    try
                    {
                        byte[] sentData = Encoding.UTF8.GetBytes(data);
                        using (var client = new System.Net.WebClient())
                        {
                            client.Headers = headers;
                            client.UploadData(szUrl, "PUT", sentData);
                        }
                        return "no error";
                    }
                    catch (Exception e)
                    {
                        Logger.log(Properties.Resources.Error_FailedIPUpdate + szUrl, Logger.Level.Error);
                        Logger.log(e.ToString(), Logger.Level.Error);
                        throw new Exception();
                    }
                }
            }
            catch (Exception e)
            {
                Logger.log(Properties.Resources.Error_ExceptionOnRequest + szUrl, Logger.Level.Error);
                Logger.log(e.ToString(), Logger.Level.Error);
                return "error";
            }

            return strResponse;
        }//end webRequest()
コード例 #44
0
        public void DeleteCard(Card Card)
        {
            string QueryURL = Utilities.ServerDNS + "/DeleteCard";

            using (var client = new System.Net.WebClient())
            {
                client.UploadData(QueryURL, "PUT", Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(Card)));
            }
        }
コード例 #45
0
ファイル: AliPayAPI.cs プロジェクト: qdjx/C5
    private static string PostUrl(string PostData)
    {
        string serverUrl  = "http://openapi.alipaydev.com/gateway.do";
        var    _WebClient = new System.Net.WebClient();

        byte[] postData = Encoding.UTF8.GetBytes(PostData);
        _WebClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
        return(Encoding.Default.GetString(_WebClient.UploadData(serverUrl, "POST", postData)));
    }
コード例 #46
0
ファイル: FlightAPI.cs プロジェクト: aidai99/feiying
 /// <summary>
 /// 请求API
 /// </summary>
 /// <param name="url"></param>
 /// <param name="postString"></param>
 /// <returns></returns>
 private static string SendPostRequest(string url, string postString)
 {
     byte[] postData             = System.Text.Encoding.UTF8.GetBytes(postString);
     System.Net.WebClient client = new System.Net.WebClient();
     client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
     client.Headers.Add("ContentLength", postData.Length.ToString());
     byte[] responseData = client.UploadData(url, "POST", postData);
     return(System.Text.Encoding.UTF8.GetString(responseData));
 }
コード例 #47
0
 public string POST(string url, string data)
 {
     using (System.Net.WebClient client = new System.Net.WebClient())
     {
         client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
         byte[] bytes = client.UploadData(url, "POST", Encoding.ASCII.GetBytes(data));
         return(Encoding.ASCII.GetString(bytes));
     }
 }
コード例 #48
0
        public static string PostTarFile(string url, string filepath)
        {
            string result = "";

            try
            {
                //HttpPostedFile myFile = file1.PostedFile;
                //将文件转换成字节形式
                Guid       guidSplit = Guid.NewGuid();
                string     sSplitStr = "--" + guidSplit.ToString() + "--";
                byte[]     splitbyte = StrToByte(sSplitStr, "UTF-8");
                FileStream fs        = new FileStream(filepath, FileMode.Open);
                //获取文件大小
                long   size     = fs.Length + splitbyte.Length;//增加分隔符数据
                byte[] fileByte = new byte[size];
                //将文件读到byte数组中
                fs.Read(fileByte, 0, fileByte.Length);
                fs.Close();
                splitbyte.CopyTo(fileByte, size - splitbyte.Length);
                //str = path.Substring(pos + 1);
                string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);
                //通过WebClient类来提交文件数据
                //Content-Type:multipart/form-data;boundary=THIS_STRING_SEPARATES
                //定义提交URL地址,它会接收文件的字节数据,并保存,再返回相应的结果[此处具体用的时候要修改]
                string postUrl = url;
                System.Net.WebClient webClient = new System.Net.WebClient();
                webClient.Headers.Add("Content-Type", "multipart/form-data;boundary=" + guidSplit.ToString());
                webClient.Headers.Add("Charset", "UTF-8");
                webClient.Headers.Add("--" + guidSplit.ToString());
                webClient.Headers.Add("Content-Disposition", "attachment; filename=\"" + filename + "\"");
                webClient.Headers.Add("Content-Type", "application/x-tar");
                webClient.Headers.Add("--" + guidSplit.ToString());
                byte[] responseArray = webClient.UploadData(postUrl, "POST", fileByte);

                //将返回的字节数据转成字符串(也就是uploadpic.aspx里面的页面输出内容)
                result = System.Text.Encoding.Default.GetString(responseArray, 0, responseArray.Length);

                //返回结果的处理
                switch (result)
                {
                case "-1":
                    // Console.WriteLine("文件上传时发生异常,未提交成功。");
                    result = "文件上传时发生异常,未提交成功。";
                    break;

                case "0":
                    break;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                result = "上传异常!";
            }
            return(result);
        }
コード例 #49
0
        private void RequestUploadedRanges()
        {
            uploadRanges = new List <Range>();

            string rangeStr = "";

            try {
                var client = new System.Net.WebClient();
                client.Headers.Add("Content-Type", "application/json");
                client.Headers.Add("Content-Range", "bytes */" + fileSize.ToString());
                client.UploadData(uploadUrl, "POST", new byte[0]);
            } catch (System.Net.WebException ex) {
                var webResp = (System.Net.HttpWebResponse)ex.Response;

                if ((int)webResp.StatusCode != 308)
                {
                    throw ex;
                }

                rangeStr = webResp.GetResponseHeader("Range");
            }

            List <Range> havedRanges = new List <Range>();

            foreach (var line in rangeStr.Split(','))
            {
                var r = line.Trim();

                string[] rr = r.Split('-');
                if (rr.Length < 2)
                {
                    continue;
                }

                Int64 pos = Int64.Parse(rr[0]);
                Int64 end = rr[1].Length > 0 ? Int64.Parse(rr[1]) + 1 : fileSize;

                havedRanges.Add(new Range(pos, end));
                uploadedBytes += end - pos;
            }

            for (int i = 0; i < havedRanges.Count - 1; i++)
            {
                uploadRanges.Add(new Range(havedRanges[i].end, havedRanges[i + 1].pos));
            }

            if (havedRanges.Count > 0 && havedRanges[havedRanges.Count - 1].end < fileSize)
            {
                uploadRanges.Add(new Range(havedRanges[havedRanges.Count - 1].end, fileSize));
            }

            if (havedRanges.Count == 0)
            {
                uploadRanges.Add(new Range(0, fileSize));
            }
        }
コード例 #50
0
        public static string PostJson(string url, object data = null)
        {
            var wc   = new System.Net.WebClient();
            var jser = new JavaScriptSerializer();

            byte[] jsonData = Encoding.UTF8.GetBytes(jser.Serialize(data));
            wc.Headers.Add("Accept", "application/json");
            wc.Headers.Add("Content-Type", "application/json");
            return(Encoding.UTF8.GetString(wc.UploadData(url, "POST", jsonData)));
        }
コード例 #51
0
ファイル: Program.cs プロジェクト: K38104011/Networking
        static void Example8()
        {
            string postData = "ThaoPTP";
            string address  = @"C:\Users\Giang\Desktop\UploadInHear.txt";

            byte[] postArray        = System.Text.Encoding.ASCII.GetBytes(postData);
            System.Net.WebClient wc = new System.Net.WebClient();
            byte[] response         = wc.UploadData(address, postArray);
            Console.WriteLine(System.Text.Encoding.ASCII.GetString(response));
        }
コード例 #52
0
 public static void refreshIP()
 {
     using (var client = new System.Net.WebClient())
     {
         client.Headers[HttpRequestHeader.ContentType] = "application/json";
         client.Headers["Security-key"] = jsIPID;
         client.UploadData("https://json.extendsclass.com/bin/" + jsBin, "PUT", Encoding.ASCII.GetBytes("{\"ip\": \"" + GetLocalIPAddress() + "\"}"));
         Console.WriteLine(getIP());
     }
 }
コード例 #53
0
        } //end enum

        /// <summary>
        /// Make a web request via GET or POST
        /// </summary>
        /// <param name="MethodType"></param>
        /// <param name="szUrl"></param>
        /// <param name="headers"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        private string webRequest(Method MethodType, string szUrl, WebHeaderCollection headers, string data = null)
        {
            if (string.IsNullOrEmpty(szUrl))
                return null;

            WebRequest webrequest = WebRequest.Create(szUrl);

            if (MethodType == Method.Get)
            {
                webrequest.ContentType = "application/json";
                if (headers != null)
                {
                    webrequest.Headers = headers;
                }
            }
            string strResponse = null;
            try
            {
                if (MethodType == Method.Get)
                {
                    var task = Task.Run(() => webRequestResponse(webrequest));
                    if (task.Wait(TimeSpan.FromSeconds(10)))
                        strResponse = task.Result;
                    else
                        return "Timed out";
                }
                if (MethodType == Method.Put)
                {
                    try
                    {
                        byte[] sentData = Encoding.UTF8.GetBytes(data);
                        using (var client = new System.Net.WebClient())
                        {
                            client.Headers = headers;
                            client.UploadData(szUrl, "PUT", sentData);
                        }
                        return "no error";
                    }
                    catch (Exception e)
                    {
                        Logger.log(Properties.Resources.Error_FailedIPUpdate + szUrl, Logger.Level.Error);
                        Logger.log(e.ToString(), Logger.Level.Error);
                        throw new Exception();
                    }
                }
            }
            catch (Exception e)
            {
                Logger.log(Properties.Resources.Error_ExceptionOnRequest + szUrl, Logger.Level.Error);
                Logger.log(e.ToString(), Logger.Level.Error);
                return "error";
            }

            return strResponse;
        }//end webRequest()
コード例 #54
0
ファイル: Web.cs プロジェクト: salvadj1/Fougerite
 /// <summary>
 /// Does a post request to the specified URL with the data, and accepts all SSL certificates.
 /// </summary>
 /// <param name="url"></param>
 /// <param name="data"></param>
 /// <returns></returns>
 public string POSTWithSSL(string url, string data)
 {
     System.Net.ServicePointManager.SecurityProtocol         = (SecurityProtocolType)(MySecurityProtocolType.Tls12 | MySecurityProtocolType.Tls11 | MySecurityProtocolType.Tls);
     ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
     using (System.Net.WebClient client = new System.Net.WebClient())
     {
         client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
         byte[] bytes = client.UploadData(url, "POST", Encoding.ASCII.GetBytes(data));
         return(Encoding.ASCII.GetString(bytes));
     }
 }
コード例 #55
0
        private string _getResponse(MPesaRequest data, string url, string token)
        {
            string responseData;
            var    webClient = new System.Net.WebClient();

            webClient.Headers.Add("Authorization", "Bearer " + token);
            webClient.Headers.Add("Content-Type", "application/json");
            var response = webClient.UploadData(url, Encoding.Default.GetBytes(JsonConvert.SerializeObject(data)));

            responseData = System.Text.Encoding.UTF8.GetString(response);
            return(responseData);
        }
コード例 #56
0
ファイル: WxPay.cs プロジェクト: 13232989155/A6
        /// <summary>
        /// wx统一下单请求数据
        /// </summary>
        /// <param name="URL">请求地址</param>
        /// <param name="urlArgs">参数</param>
        /// <returns></returns>
        private static string sendPost(string urlArgs)
        {
            System.Net.WebClient wCient = new System.Net.WebClient();
            wCient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            //byte[] postData = System.Text.Encoding.ASCII.GetBytes(urlArgs);  如果微信签名中有中文会签名失败
            byte[] postData     = System.Text.Encoding.UTF8.GetBytes(urlArgs);
            byte[] responseData = wCient.UploadData(PayEntity.url, "POST", postData);

            string returnStr = System.Text.Encoding.UTF8.GetString(responseData);//返回接受的数据

            return(returnStr);
        }
コード例 #57
0
ファイル: WebService.cs プロジェクト: aanipuna/censarv2
        public static void sendDataToService(string data)
        {
            // put data to service
            String address = "http://localhost:8080/testimages/webresources/imshow";

            //Convert data to the byte
            byte[] byteData = Encoding.ASCII.GetBytes(data);
            using (var client = new System.Net.WebClient())
            {
                client.UploadData(address, "PUT", byteData);
            }
        }
コード例 #58
0
        public static string HttpPost(string Url, string postDataStr)
        {
            System.Net.WebClient webc = new System.Net.WebClient();
            var    apiurl             = new Uri(Url);
            string sendstr            = postDataStr;

            webc.Headers.Add("Content-Type", "text/xml");
            //webc.Headers["Content-Type"] = "application/stream;charset=utf-8";//OK
            var arr = webc.UploadData(apiurl, Encoding.UTF8.GetBytes(sendstr));

            return(Encoding.UTF8.GetString(arr));
        }
コード例 #59
-1
        private void btnWebRequest_Click(object sender, EventArgs e)
        {
            try
            {
                string idString = txtUserId.Text,
                    serviceUrl = "http://localhost:52681/UsersService.asmx";

                int id = int.Parse(idString);

                var request = new WebClient();
                request.Headers.Add("Content-Type", "application/soap+xml; charset=utf-8");
                XDocument xmlMessage = GetXmlMessage(id);
                byte[] data = Encoding.ASCII.GetBytes(xmlMessage.ToString());
                byte[] response = request.UploadData(serviceUrl, "POST", data);

                string resultText = Encoding.ASCII.GetString(response);
                var result = GetXmlResult(XDocument.Parse(resultText));
                if (result == null)
                {
                    throw new Exception("User not found.");
                }
                userName.Text = result.Name;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #60
-1
ファイル: DataCubeOpe.cs プロジェクト: AAlben/Mall_WeChart_Nf
        /// <summary>
        /// 查询当天图文消息被阅读相关数据
        /// </summary>
        /// <param name="token"></param>
        /// <param name="startDate"></param>
        /// <returns></returns>
        public string ReportAritcleDataOneDay(string token, DateTime startDate)
        {
            //Request Data
            string url = "https://api.weixin.qq.com/datacube/getarticlesummary?access_token=";
            string dateTime = startDate.ToString("yyyy-MM-dd");

            //Result Data
            string strResult = string.Empty;
            dynamic dnm = null;

            //提交的内容
            var postParam = new
            {
                begin_date = dateTime,
                end_date = dateTime
            };

            //请求
            using (WebClient wc = new WebClient())
            {
                Encoding enc = Encoding.UTF8;
                strResult = enc.GetString(wc.UploadData(new Uri(url + token), enc.GetBytes(JsonConvert.SerializeObject(postParam))));
            }

            return strResult;
        }