当前位置: 首页>>代码示例>>C#>>正文


C# HttpClient.Post方法代码示例

本文整理汇总了C#中System.Net.Http.HttpClient.Post方法的典型用法代码示例。如果您正苦于以下问题:C# HttpClient.Post方法的具体用法?C# HttpClient.Post怎么用?C# HttpClient.Post使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Http.HttpClient的用法示例。


在下文中一共展示了HttpClient.Post方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

        static void Main(string[] args)
        {
            CookieContainer cookieContainer = new CookieContainer();
            using (HttpClient client = new HttpClient("http://localhost:44857/")) {
                HttpClientChannel clientChannel = new HttpClientChannel();
                clientChannel.CookieContainer = cookieContainer;
                client.Channel = clientChannel;
                HttpContent loginData = new FormUrlEncodedContent(
                    new List<KeyValuePair<string, string>>
                        {
                            new KeyValuePair<string, string>("Username", "foo"),
                            new KeyValuePair<string, string>("Password", "bar")
                        }
                    );
                client.Post("login", loginData);
            }

            string result = string.Empty;
            using (HttpClient client = new HttpClient("http://localhost:44857/contact/")) {
                HttpClientChannel clientChannel = new HttpClientChannel();
                clientChannel.CookieContainer = cookieContainer;
                client.Channel = clientChannel;
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = client.Get("1");
                result = response.Content.ReadAsString();
            }

            JavaScriptSerializer jsonDeserializer = new JavaScriptSerializer();
            ContactDto contact = jsonDeserializer.Deserialize<ContactDto>(result);
            Console.WriteLine(contact.Name);
            Console.ReadLine();
        }
开发者ID:AlexZeitler,项目名称:WcfHttpMvcFormsAuth,代码行数:32,代码来源:Program.cs

示例2: UpdloadFileForSharing

        public Guid UpdloadFileForSharing(string filename,string apiKey, string projectName /*,string ownerEmail*/)
        {
            if (string.IsNullOrWhiteSpace(filename)) { throw new ArgumentNullException("filename"); }
            if (string.IsNullOrWhiteSpace(apiKey)) { throw new ArgumentNullException("apiKey"); }
            if (string.IsNullOrWhiteSpace(projectName)) { throw new ArgumentNullException("projectName"); }
            // if (string.IsNullOrWhiteSpace(ownerEmail)) { throw new ArgumentNullException("ownerEmail"); }
            if (!File.Exists(filename)) {
                throw new FileNotFoundException(filename);
            }

            string baseUrl = Settings.Default.LocanServiceBaseUrl;

            string urlForSharing = string.Format(
                "{0}/{1}",
                baseUrl,
                Consts.UrlAddPhrasesForTranslation);

            Guid userId = this.GetUserIdForApiKey(apiKey);
            LocanWebFile webFile = this.GetTranslationFile(apiKey, filename, userId, projectName);
            JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
            byte[]bytes = Encoding.UTF8.GetBytes(jsonSerializer.Serialize(webFile));

            using (HttpClient client = new HttpClient())
            using(MemoryStream stream = new MemoryStream(bytes)){
                StreamContent streamContent = new StreamContent(stream);
                HttpResponseMessage response = client.Post(urlForSharing, streamContent);
                response.EnsureSuccessStatusCode();
                string guidString = response.Content.ReadAsString();
                // Result looks like: <?xml version="1.0" encoding="utf-8"?><guid>2158e8e5-ae6c-4b9a-a7ab-3169fff9750d</guid>
                XDocument doc = XDocument.Parse(guidString);
                return new Guid(doc.Root.Value);
            }
        }
开发者ID:sayedihashimi,项目名称:locan,代码行数:33,代码来源:TranslationManager.cs

示例3: Main

    static public void Main ()
    {
        Console.WriteLine ("Trying to send");
        var username = "<API Username>";
        var password = "<API Password>";
        var postData = new List<KeyValuePair<string, string>>()
            {
            new KeyValuePair<string, string>("from", "+4676865201"),
            new KeyValuePair<string, string>("to", "+46723175800"),
            new KeyValuePair<string, string>("voice_start", '{"connect":"+461890510"}')
            };
                                
        string creds = string.Format("{0}:{1}", username, password);
        byte[] bytes = Encoding.ASCII.GetBytes(creds);
        var header = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(bytes));
        var content = new FormUrlEncodedContent(postData);
        
        HttpClient Client = new HttpClient();
        Client.DefaultRequestHeaders.Authorization = header;
            
        var responseMessage =  Client.Post("https://api.46elks.com/a1/Calls", content);
        var response = esponseMessage.Content.ReadAsString();
        Console.WriteLine (response);
    }
}
开发者ID:46elks,项目名称:46elks-getting-started,代码行数:25,代码来源:csharp.cs

示例4: WhenPostingAPersonThenResponseIndicatesPersonWasAdded

 public void WhenPostingAPersonThenResponseIndicatesPersonWasAdded()
 {
     HelloResource.Initialize(new List<string>());
     using (var host = new HttpServiceHost(typeof(HelloResource), this.hostUri))
     {
         host.Open();
         var client = new HttpClient();
         var response = client.Post(this.hostUri, new StringContent("person=Glenn", Encoding.UTF8, "application/x-www-form-urlencoded"));
         Assert.AreEqual("Added Glenn", response.Content.ReadAsString());
     }
 }
开发者ID:nuxleus,项目名称:WCFWeb,代码行数:11,代码来源:HelloResourceAcceptanceTest.cs

示例5: Post_of_a_valid_message

        public void Post_of_a_valid_message()
        {
            var client = new HttpClient(baseUri);
            var content = new StringContent("sample");

            var topicId = Identity.Random();
            var response = new Message {Id = Identity.Random() };

            createMessageCommand
                .Setup(s => s.Execute(It.Is<Message>(m => m != null && m.TopicId == topicId)))
                .Callback<Message>(m => m.Id = Identity.Random()); ;

            var httpResponse = client.Post(baseUri+"/topic/" + topicId, content);

            var contentStr = httpResponse.Content.ReadAsString();
        }
开发者ID:ashic,项目名称:Hermes,代码行数:16,代码来源:MessagesFixture.cs

示例6: AddNewEarthwatcherHttpClient

        // client using httpclient, sample for http post with authentication
        private static bool AddNewEarthwatcherHttpClient(string tigUser, string username, string password)
        {
            var httpClient = new HttpClient();
            dynamic tigmember = new ExpandoObject();
            tigmember.Name = tigUser;
            var json=JsonConvert.SerializeObject(tigmember);
            var content = new StringContent(json);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            
            var authstring=Base64Helper.ToBase64String(string.Format("{0}:{1}", username,password));

            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authstring);
            // send the request
            bool isSuccess = httpClient.Post(Server + "earthwatchers", content).IsSuccessStatusCode;
            return isSuccess;
        }
开发者ID:HackatonArGP,项目名称:Guardianes,代码行数:17,代码来源:Program.cs

示例7: GetAccessTokenFromCode

        public async Task<GetAccessTokenFromCodeResponse> GetAccessTokenFromCode(string code, string clientId, string redirectUri)
        {
            var client = new HttpClient()
            {
                BaseAddress = new Uri(_authUri)
            };
            client.DefaultRequestHeaders.Authorization = BasicAuthHeader.GetHeader(clientId, _secretKey);

            var parameters = new Dictionary<string, string>()
            {
                {"grant_type", "authorization_code"},
                {"code", code},
                {"redirect_uri", redirectUri}
            };

            var response = await client.Post<GetAccessTokenFromCodeResponse>("connect/token", parameters);

            return response.Data;
        }
开发者ID:bjcull,项目名称:Pinch.SDK,代码行数:19,代码来源:AuthClient.cs

示例8: TryUpload

        public void TryUpload(Stream stream, string name)
        {
            using (var client = new HttpClient(baseUrl))
            {
                var fileContent = new StreamContent(stream);
                var content = new MultipartFormDataContent { { fileContent, "UploadFile", name } };
                var response = client.Post("upload?AutoResize=true", content);
                var serializer = new DataContractJsonSerializer(typeof(FileUploadResponse));
                var streamReader = response.Content.ContentReadStream;
                response.EnsureSuccessStatusCode();

                var rspObject = serializer.ReadObject(streamReader) as FileUploadResponse;

                CheckSuccessfulUpload(rspObject);

                Clipboard.SetDataObject(rspObject.redirectTo, true);
                var form = new ResponseForm(rspObject);
                form.ShowDialog();
            }
        }
开发者ID:eservicepartner,项目名称:espUrl,代码行数:20,代码来源:EspUrlClient.cs

示例9: CreateRepository

        public string CreateRepository(string repositoryName, out string errorMessage)
        {
            errorMessage = null;
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            client = new System.Net.Http.HttpClient();
            client.DefaultRequestHeaders.Add("user-agent", "SF-Client");
            var newRepo = (dynamic)new JsonObject();
            newRepo.name = repositoryName;

            var response = client.Post("https://api.github.com/user/repos?access_token=" + authorizator.SignedMemberToken,
                new StringContent(newRepo.ToString(), System.Text.Encoding.UTF8, "application/json"));

            if (!response.IsSuccessStatusCode) {
                string msg = response.Content.ReadAsString();
                errorMessage = "Error creating repo: " + response.StatusCode + "\n" + msg;
                return null;
            }
            dynamic repo = response.Content.ReadAs<JsonObject>();

            return (string)repo.svn_url;
        }
开发者ID:klot-git,项目名称:scrum-factory,代码行数:21,代码来源:GithubCodeRepositoryService.cs

示例10: GetAccessTokenFromSecretKey

        public async Task<GetAccessTokenFromSecretKeyResponse> GetAccessTokenFromSecretKey(string secretKey, string clientId)
        {
            var client = new HttpClient()
            {
                BaseAddress = new Uri(_authUri)
            };
            client.DefaultRequestHeaders.Authorization = BasicAuthHeader.GetHeader(clientId, secretKey);

            var parameters = new Dictionary<string, string>()
            {
                {"grant_type", "client_credentials"},
                {"scope", "api1"}
            };            

            var response = await client.Post<GetAccessTokenFromSecretKeyResponse>("connect/token", parameters);            
                
            if (response.Data?.AccessToken == null)
            {
                throw new Exception($"Could not get access token. Error: {response.ResponseBody}");
            }

            return response.Data;
        }
开发者ID:bjcull,项目名称:Pinch.SDK,代码行数:23,代码来源:AuthClient.cs

示例11: TestCreate

        public void TestCreate()
        {
            using (var webservice = CreateRESTHttpService())
            {
                var client = new HttpClient();
                client.BaseAddress = webservice.BaseUri;

                // Builds: http://localhost:20259/RESTEmployeeService.svc/Create

                var uri = webservice.Uri("Create");

                var employee = new Employee()
                {
                    ContactID = 1,
                    ManagerID = 23,
                    Title = "Engineer",
                    BirthDate = DateTime.Now.AddYears(-23),
                    Gender = "1",
                    CurrentFlag = false,
                    HireDate = DateTime.Now,
                    ModifiedDate = DateTime.Now,
                    NationalIDNumber = "32323"
                };

                var httpcontent = new FormUrlEncodedContent(GetEntityToListKeyValuePair(employee));
                var response = client.Post(uri, httpcontent);

                Assert.True(response.IsSuccessStatusCode, response.ToString());
                Assert.True(response.Content.ReadAsString().Contains("true"));
            }
        }
开发者ID:yonglehou,项目名称:ironframework,代码行数:31,代码来源:RESTServiceTest.cs

示例12: GetAuthorizationToken

        public override bool GetAuthorizationToken(string user, string pass)
        {
            var data = new GitAuthenticationRequest() { client_id = ClientId, client_secret = ClientSecret, note = "scrum factory login", scopes = "public_repo" };

            string _auth = string.Format("{0}:{1}", user, pass);
            string _enc = Convert.ToBase64String(Encoding.UTF8.GetBytes(_auth));

            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            client.DefaultRequestHeaders.Add("user-agent", "SF-Client");
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", _enc);

            var response = client.Post("https://api.github.com/authorizations", new ObjectContent<GitAuthenticationRequest>(data, JsonMediaTypeFormatter.DefaultMediaType));

            if (!response.IsSuccessStatusCode) {
                string r = response.Content.ReadAsString();
                log.LogText(r);
                return false;
            }

            dynamic obj = response.Content.ReadAs<JsonObject>();

            AUTH_TOKEN = obj.token;
            ACCESS_TOKEN = obj.token;
            REFRESH_TOKEN = null;
            Properties.Settings.Default.Save();

            return true;
        }
开发者ID:klot-git,项目名称:scrum-factory,代码行数:28,代码来源:GitHubAuthorizationProvider.cs


注:本文中的System.Net.Http.HttpClient.Post方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。