本文整理汇总了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();
}
示例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);
}
}
示例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);
}
}
示例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());
}
}
示例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();
}
示例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;
}
示例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;
}
示例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();
}
}
示例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;
}
示例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;
}
示例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"));
}
}
示例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;
}