1. 程式人生 > >對WebApi的三種請求方式(以post上傳為例):HttpClient,WebClient,HttpWebRequest

對WebApi的三種請求方式(以post上傳為例):HttpClient,WebClient,HttpWebRequest

WebClient

WebClient client = new WebClient();
byte[] bytes = client.UploadFile("http://ip:port/api/Image/UploadAndStoreDicom", fileName);
string str = System.Text.Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);
public void HttpUpload(string url)
{
	byte[] bytes;
	using(FileStream fs = new
FileStram("filename",FileMode.Open,FileAccess.Read)) { bytes = new byte[fs.Length]; fs.Read(bytes,0,bytes.Length); fs.Seek(0,SeekOrigin.Begin); fs.Read(bytes,0,Convert.ToInt32(fs.Length)); } string postData = "UploadFile=" + HttpUtility.UrlEncode(Convert.ToBase64String(bytes)); var webClient =
new WebClient(); webClient.Headers.Add("Content-Type","application/x-www-form-urlencoded"); byte[] byteArray = Encoding.UTF8.GetBytes(postData); byte[] buffer = webClient.UploadData(url,"POST",byteArray); }

HttpWebRequest

public string HttpUpload(string url)
{
	byte[] bytes;
	using(FileStream fs =
new FileStream("filename",FileMode.Open,FileAccess.Read)) { bytes = new byte[fs.Length]; fs.Read(bytes,0,bytes.Length); fs.Seek(0,SeekOrigin.Begin); } HttpWebRequest rq = (HttpWebRequest)HttpWebRequest.Create(url); rq.ContentType = "application/x-www-form-urlencoded"; rq.Method = "POST"; rq.ContentLength = bytes.Length; rq.ContinueTimeout = 300000; using(StreamWriter dataStream = new StreamWriter(rq.GetRequestStream())) { dataStream.Write(bytes,0,bytes.Length); dataStream.Flush(); dataStream.Close(); } HttpWebResponse response = (HttpWebResponse)rq.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { string body = reader.ReadToEnd(); reader.Close(); return body; } }

HttpClient

參考部落格:https://blog.csdn.net/zknxx/article/details/72760315