对WebApi的三种请求方式(以post上传为例):HttpClient,WebClient,HttpWebRequest

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_41556165/article/details/83653503

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

猜你喜欢

转载自blog.csdn.net/weixin_41556165/article/details/83653503
今日推荐