本文整理汇总了C#中System.Net.Http.HttpClient.PostAsync方法的典型用法代码示例。如果您正苦于以下问题:C# System.Net.Http.HttpClient.PostAsync方法的具体用法?C# System.Net.Http.HttpClient.PostAsync怎么用?C# System.Net.Http.HttpClient.PostAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Http.HttpClient
的用法示例。
在下文中一共展示了System.Net.Http.HttpClient.PostAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ImageToStream
public async Task<string> ImageToStream(byte[] image)
{
try
{
System.Diagnostics.Debug.WriteLine(image.Length);
using (var client = new System.Net.Http.HttpClient())
{
using (var content =
new System.Net.Http.MultipartFormDataContent())
{
content.Add(new System.Net.Http.StreamContent(new MemoryStream(image)), "file", "upload.jpg");
using (
var message =
await client.PostAsync("http://bbs.jiangnan.edu.cn/attachments/upload.php", content))
{
message.EnsureSuccessStatusCode();
string finalresults = await message.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine(finalresults);
return finalresults;
}
}
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
return e.Message;
}
}
示例2: sendRequestAsync
/// <summary>
/// Send a pre-serialized OFX request to the service, retrieve the response and deserialize into an OFX object.
///
/// This is an asycronous call.
/// </summary>
/// <param name="request">Populated OFX request object</param>
/// <returns>The returned task includes a populated OFX response object on successfull call</returns>
public async Task<Protocol.OFX> sendRequestAsync(StreamContent request)
{
// Create an HTTPClient to send the request
using (var client = new System.Net.Http.HttpClient())
{
// OFX endpoints do not use 100 Continue responses. Disable default .NET expectation of them.
client.DefaultRequestHeaders.ExpectContinue = false;
// POST request and await response
var response = await client.PostAsync(m_serviceURI.ToString(), request).ConfigureAwait(false);
// Read into stream
var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
// Deserialize XML stream into object - try directly deserializing
try
{
return (Protocol.OFX) m_serializer.Deserialize(responseStream);
}
catch (System.InvalidOperationException)
{
// This is sometimes thrown when the response is actually UTF-8, but the xml marker claims utf-16
responseStream.Position = 0;
var streamReader = new StreamReader(responseStream, Encoding.UTF8);
return (Protocol.OFX)m_serializer.Deserialize(streamReader);
}
}
}
示例3: PostStringAsync2
public async Task<string> PostStringAsync2(string link, List<KeyValuePair<string, string>> values)
{
var httpClient = new System.Net.Http.HttpClient(new System.Net.Http.HttpClientHandler());
System.Net.Http.HttpResponseMessage response = await httpClient.PostAsync(new Uri(link), new System.Net.Http.FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine(response.Headers);
return responseString;
}
示例4: getHttpWebRequest
public static async Task<string> getHttpWebRequest(string api, List<KeyValuePair<String, String>> paramList = null, int PostORGet = 0, bool fulluri = false)
{
string content = "";
return await Task.Run(() =>
{
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
try
{
System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
string uri;
if (!fulluri)
uri = "http://hongyan.cqupt.edu.cn/" + api;
else
uri = api;
httpClient.DefaultRequestHeaders.Add("API_APP", "winphone");
httpClient.DefaultRequestHeaders.Add("API_TOKEN", "0zLUZA0j+OL77OsjXC0ulOz50KaI6yANZtkOk2vQIDg=");
System.Net.Http.HttpRequestMessage requst;
System.Net.Http.HttpResponseMessage response;
if (PostORGet == 0)
{
requst = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, new Uri(uri));
response = httpClient.PostAsync(new Uri(uri), new System.Net.Http.FormUrlEncodedContent(paramList)).Result;
}
else
{
requst = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, new Uri(uri));
response = httpClient.GetAsync(new Uri(uri)).Result;
}
if (response.StatusCode == HttpStatusCode.OK)
content = response.Content.ReadAsStringAsync().Result;
//else if (response.StatusCode == HttpStatusCode.NotFound)
// Utils.Message("Oh...服务器又跪了,给我们点时间修好它");
}
catch (Exception e)
{
Debug.WriteLine(e.Message + "网络请求异常");
}
}
else
{
}
//if (content.IndexOf("{") != 0)
// return "";
//else
return content;
});
}
示例5: MakeTheCallAsync
async System.Threading.Tasks.Task<bool> MakeTheCallAsync()
{
string caller = PhoneNumbers[FromNumber];
if (caller == null)
throw new ArgumentException(FromNumber.ToString(), "FromNumber");
if (String.IsNullOrEmpty(ToNumber))
throw new ArgumentException(ToNumber ?? "null", "ToNumber");
string xml = null;
if (1 < NRepeatAll)
{
var say = new System.Xml.XmlDocument().CreateElement("Say");
say.InnerText = Message;
xml = "<Response>" + String.Join("<Pause length=\"2\"/>", Enumerable.Repeat(say.OuterXml, NRepeatAll)) + "</Response>";
}
var client = new System.Net.Http.HttpClient(); // System.Net.Http.dll
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(TwilioSid + ":" + TwilioToken)));
try
{
System.Net.Http.HttpResponseMessage response = await client.PostAsync(
"https://api.twilio.com/2010-04-01/Accounts/" + TwilioSid + "/Calls.json", // could be .csv as well, see https://www.twilio.com/docs/api/rest/tips
new System.Net.Http.FormUrlEncodedContent(new Dictionary<string, string>() {
{ "From", caller },
{ "To", ToNumber },
{ "Method", "GET" },
{ "Url", xml != null ? "http://twimlets.com/echo?Twiml=" + Uri.EscapeDataString(xml)
: "http://twimlets.com/message?Message%5B0%5D=" + Uri.EscapeDataString(Message) } // O.K.
//{ "Url", "http://twimlets.com/message?" + Uri.EscapeDataString("Message[0]=" + p_message) } // <Response/> -- successful but empty call
//{ "Url", "http://twimlets.com/message?Message%5B0%5D=Hello+this+is+a+test+call+from+Twilio." } // O.K.
//{ "Url", "http://twimlets.com/message?Message[0]=Hello%2C+this+is+a+test+call+from+Twilio." } // Error: 11100 Invalid URL format
//{ "Url", "http://twimlets.com/message?Message[0]=Hello,+this+is+a+test+call+from+Twilio." } // Error: 11100 Invalid URL format
//{ "Url", "http://twimlets.com/message?Message[0]=" + Uri.EscapeDataString(p_message) } // Error: 11100 Invalid URL format
//{ "Url", "http://www.snifferquant.com/robin/twimlet.xml" } // O.K.
}));
string resp = await response.Content.ReadAsStringAsync();
if (resp.StartsWith("{\"sid\":"))
ResultJSON = resp;
else
Error = resp;
}
catch (Exception e)
{
Error = ToStringWithoutStackTrace(e);
//Program.gLogger.Info("Error: " + Error);
Console.WriteLine("Error: " + Error);
}
return Error == null;
}
示例6: getTransaction
public static async Task<string> getTransaction(string api, List<KeyValuePair<string, string>> paramList)
{
return await Task.Run(() =>
{
string content = "";
System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
System.Net.Http.HttpResponseMessage response = httpClient.PostAsync(new Uri(api), new System.Net.Http.FormUrlEncodedContent(paramList)).Result;
if (response.StatusCode == HttpStatusCode.OK)
{
content = response.Content.ReadAsStringAsync().Result;
Debug.WriteLine(content);
}
return content;
});
}
示例7: GetAccessToken
protected override string GetAccessToken(string authCode)
{
System.Net.Http.HttpClient wc = new System.Net.Http.HttpClient();
string postData = "code={0}&client_id={1}&redirect_uri={2}&grant_type={3}&client_secret={4}";
postData = string.Format(postData,
HttpUtility.UrlEncode(authCode),
CLIENT_ID,
HttpUtility.UrlEncode(CALLBACK_URL),
"authorization_code",
SECRET);
System.Net.Http.HttpResponseMessage msg = wc.PostAsync(GET_TOKEN_URL, new System.Net.Http.StringContent(postData, Encoding.Default, "application/x-www-form-urlencoded")).Result;
if (msg.StatusCode == System.Net.HttpStatusCode.OK)
return msg.Content.ReadAsStringAsync().Result.Replace("access_token=", "");
return null;
}
示例8: do_reportBuildShip
private static void do_reportBuildShip(int dockid, BSLOG bSLOG, GetShipData getShipData)
{
if (getShipData == null || getShipData.shipVO == null )
{
return;
}
var dic = new Dictionary<string, string>();
string desc = "";
UserShip flagship = GameData.instance.GetShipById(GameData.instance.UserFleets[0].ships[0]);
UserShip us = getShipData.shipVO;
{
desc += bSLOG.oil.ToString() + "|" +
bSLOG.ammo.ToString() + "|" +
bSLOG.steel.ToString() + "|" +
bSLOG.al.ToString() + "|" +
bSLOG.timetick.ToString() + "|" +
bSLOG.buildreturntype.ToString() +
"|" + us.ship.cid + "|" + us.ship.title + "|" + us.ship.star
+ "|" + ServerTimer.GetNowServerTime()
+ "|" + z.instance.getServerName()
+ "|" + flagship.level + "|" + flagship.ship.cid + "|" + flagship.ship.luck + "|" + flagship.ship.star + "|" + flagship.ship.title
+ "|" + GameData.instance.UserInfo.detailInfo.collection
+ "|" + GameData.instance.UserInfo.level
+ "\r\n";
}
dic["msg"] = desc;
var c = new System.Net.Http.FormUrlEncodedContent(dic);
try
{
var p = new System.Net.Http.HttpClient();
var r = p.PostAsync(tools.helper.count_server_addr + "/sssgbsssgb/reportbuild", c).Result;
}
catch (Exception)
{
}
}
示例9: PasteCard
public static async Task<String> PasteCard(Card c)
{
var httpclient = new System.Net.Http.HttpClient();
var content = new System.Net.Http.MultipartFormDataContent();
Dictionary<String, String> formData = new Dictionary<String, String>();
content.Add(new System.Net.Http.StringContent(API_KEY), "api_dev_key");
content.Add(new System.Net.Http.StringContent("paste"), "api_option");
content.Add(new System.Net.Http.StringContent(String.Format("Debug data for {0}", c.Name)), "api_paste_name");
content.Add(new System.Net.Http.StringContent(String.Format("Source: {0}\n\n{1}", c.XmlSource, c.XmlData)), "api_paste_code");
var response = await httpclient.PostAsync("http://pastebin.com/api/api_post.php", content);
if (!response.IsSuccessStatusCode)
return null;
return await response.Content.ReadAsStringAsync();
// var request = System.Net.HttpWebRequest.Create("http://pastebin.com/api/api_post.php");
// request.Method = "POST";
}
示例10: SendToApi
public static void SendToApi()
{
string[] uploadfiles = new string[] { "D:\\2d.jpg", "d:\\140317.ajk" }; //上传文件路径
string url = "http://localhost:49840//api/fileapi"; //服务地址
using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
{
using (var content = new System.Net.Http.MultipartFormDataContent())//表明是通过multipart/form-data的方式上传数据
{
//循环添加文件至列表
foreach (var path in uploadfiles)
{
var fileContent = new System.Net.Http.ByteArrayContent(System.IO.File.ReadAllBytes(path));
fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = System.IO.Path.GetFileName(path),//此处可以自定义文件名
};
content.Add(fileContent);
}
var result = client.PostAsync(url, content).Result;//提交post请求
}
}
}
示例11: Authorized
public IActionResult Authorized(string code)
{
OauthInfo oai = OauthRepository.Get();
if (code == null)
return View(oai);
oai.authCode = code;
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
var url = "https://graph.api.smartthings.com/oauth/token";
List<KeyValuePair<string, string>> parms = new List<KeyValuePair<string, string>>();
parms.Add(new KeyValuePair<string, string>("grant_type", "authorization_code"));
parms.Add(new KeyValuePair<string, string>("code", oai.authCode));
parms.Add(new KeyValuePair<string, string>("client_id", oai.clientKey));
parms.Add(new KeyValuePair<string, string>("client_secret", oai.secretKey));
string authorizedUrl = "http://" + this.Request.Host.Value + this.Url.Content("~/OAuth/Authorized");
parms.Add(new KeyValuePair<string, string>("redirect_uri", authorizedUrl));
var content = new System.Net.Http.FormUrlEncodedContent(parms);
var response = client.PostAsync(url, content);
response.Wait();
if (response.Result.StatusCode != System.Net.HttpStatusCode.OK)
{
ViewData.Add("GetTokenError", "Get Auth Code Error: " + response.Result.StatusCode.ToString());
return View(oai);
}
// Save the interim result
var val = JsonConvert.DeserializeObject<Dictionary<string, string>>(response.Result.Content.ReadAsStringAsync().Result);
oai.accessToken = val["access_token"];
oai.expiresInSeconds = Convert.ToInt32(val["expires_in"]);
oai.tokenType = val["token_type"];
OauthRepository.Save(oai);
// Get the endpoint info
client = new System.Net.Http.HttpClient();
url = "https://graph.api.smartthings.com/api/smartapps/endpoints";
System.Net.Http.HttpRequestMessage msg = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
msg.Headers.Add("Authorization", $"Bearer {oai.accessToken}");
response = client.SendAsync(msg);
response.Wait();
if (response.Result.StatusCode != System.Net.HttpStatusCode.OK)
{
ViewData.Add("GetTokenError", "Get EndPoints Error: " + response.Result.StatusCode.ToString());
return View(oai);
}
string jsonString = response.Result.Content.ReadAsStringAsync().Result;
oai.endpoints = JsonConvert.DeserializeObject<List<OauthEndpoint>>(jsonString);
OauthRepository.Save(oai);
// Install the Zones
SmartThingsRepository.InstallDevices(this.Request.Host.Value);
return View(oai);
}
示例12: CaptureAsJPEG
public static void CaptureAsJPEG()
{
using (var client = new System.Net.Http.HttpClient())
{
client.DefaultRequestHeaders.ExpectContinue = false; //REQUIRED! or you will get 502 Bad Gateway errors
var pageRequestJson = new System.Net.Http.StringContent(File.ReadAllText("request.json"));
var response = client.PostAsync("https://PhantomJScloud.com/api/browser/v2/a-demo-key-with-low-quota-per-ip-address/", pageRequestJson).Result;
var responseStream = response.Content.ReadAsStreamAsync().Result;
//using (var fileStream = new FileStream("content123455.jpg", FileMode.Create))
//{
// responseStream.CopyTo(fileStream);
//}
using (StreamReader myStreamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")))
{
string retString = myStreamReader.ReadToEnd();
}
var ms = new MemoryStream();
responseStream.CopyTo(ms);
//responseStream.Position = 0;
//byte[] buffer = new byte[2048];
//int bytesRead = 0;
//while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) != 0)
//{
// ms.Write(buffer, 0, bytesRead);
//}
ms.Position = 0;
Bitmap destBmp = new Bitmap(ms);//create bmp instance from stream above
destBmp.Save(@"D:\work\He\CommonTest\PhantomJsConsole\bin\Debug\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg");//save bmp to the path you want
//var image = System.Drawing.Image.FromStream(ms);
//image.Save(@"D:\work\He\CommonTest\PhantomJsConsole\bin\Debug\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg");
//ms.Close();
Console.WriteLine("*** Headers, pay attention to those starting with 'pjsc-' ***");
Console.WriteLine(response.Headers);
}
}
示例13: Request
public static object Request(object request, Type responseType=null, bool post=false)
{
/** determine the api method to call */
string method = Mozu.getMethod(request);
if (responseType == null) responseType = request.GetType();
/** make sure we have a valid authentication ticket */
if (_auth == null && request.GetType() != typeof(AuthenticationContract)) Mozu.authenticate();
string url = string.Format("{0}{1}", _apiUrl, method);
Type t = request.GetType();
bool get = false;
if (! post && (t == typeof(CustomerAccount) || t == typeof(Product) || t == typeof(Order))) {
url = "https://t7949.sandbox.mozu.com";
get = true;
}
else if (post && (t == typeof(CustomerAccount) || t == typeof(Product) || t == typeof(Order))) {
url = "https://t7949.sandbox.mozu.com/api/platform";
}
//HTTP http = new HTTP();
Console.WriteLine("Calling Mozu API: " + url);
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient { BaseAddress = new Uri(url) };
//if (request.GetType() != typeof(AuthenticationContract)) http.AddHeader("x-vol-app-claims", _auth.Ticket.AccessToken);
if (t != typeof(AuthenticationContract)) {
client.DefaultRequestHeaders.Add("x-vol-app-claims", _auth.Ticket.AccessToken);
client.DefaultRequestHeaders.Add("x-vol-tenant", "7949");//the sandbox number
if (t == typeof(Product)) {
client.DefaultRequestHeaders.Add("x-vol-master-catalog", "2");
}
//client.DefaultRequestHeaders.Add("x-vol-catalog", "1");
//client.DefaultRequestHeaders.Add("x-vol-version", "1.9.14232.3");
}
string json = JSON.Serialize(request);
//string response = http.POSTRaw(url, json, "application/json");
string response = null;
if (get) {
method = "/api" + method;
if (t == typeof(Product)) method += "?startindex=0&pagesize=200";
var r = client.GetAsync(method).Result;
response = r.Content.ReadAsStringAsync().Result;
}
else {
var r = client.PostAsync("/api" + method, new System.Net.Http.StringContent(json, System.Text.Encoding.UTF8, "application/json")).Result;
response = r.Content.ReadAsStringAsync().Result;
}
object o = JSON.Deserialize(response, responseType);
return o;
}
示例14: PostJsonDataAsyncAttempt
/// <summary>
/// POST JSON data to the specified mongoDB collection.
/// </summary>
async void PostJsonDataAsyncAttempt(
string collection_name,
string json )
{
using( System.Net.Http.HttpClient httpClient
= new System.Net.Http.HttpClient() )
{
try
{
string resourceAddress = Util.RestApiUri
+ "/" + collection_name;
string postBody = json;
httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json" ) );
HttpResponseMessage wcfResponse
= await httpClient.PostAsync(
resourceAddress, new StringContent(
postBody, Encoding.UTF8,
"application/json" ) );
//await DisplayTextResult( wcfResponse, OutputField );
}
catch( HttpRequestException hre )
{
Util.Log( "Error:" + hre.Message );
}
catch( TaskCanceledException )
{
Util.Log( "Request canceled." );
}
catch( Exception ex )
{
Util.Log( ex.Message );
}
}
}
示例15: button3_Click
/// <summary>
/// 调用第三方PhantomJs
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
using (var client = new System.Net.Http.HttpClient())
{
client.DefaultRequestHeaders.ExpectContinue = false; //REQUIRED! or you will get 502 Bad Gateway errors
var pageRequestJson = new System.Net.Http.StringContent(System.IO.File.ReadAllText("request.json"));
var response = client.PostAsync("https://PhantomJScloud.com/api/browser/v2/a-demo-key-with-low-quota-per-ip-address/", pageRequestJson).Result;
var responseStream = response.Content.ReadAsStreamAsync().Result;
using (var fileStream = new System.IO.FileStream("content.jpg", System.IO.FileMode.Create))
{
responseStream.CopyTo(fileStream);
}
Console.WriteLine("*** Headers, pay attention to those starting with 'pjsc-' ***");
Console.WriteLine(response.Headers);
}
}