WebClient和HttpWebRequest 上传文件
这几天对接淘宝的上传航司政策的接口。对期间出现的问题,以及使用WebClient和HttpWebReques 上传文件进行总结。本文重要信息已使用'*'代替
1.WebClient上传文件
使用UploadFile上传文件,其中fileNamePath为物理路径。
public bool UpLoadFile(string fileNamePath,string url) { string timeStamp = DateTime.Now.ToString("YYYY-MM-DD HH:mm:ss"); string userName = "*****"; string passWord = "*****"; string uniqueKey = "*****"; string userkey = Md5Helper.GetMD5String(userName + passWord + uniqueKey + timeStamp); _webClient.Headers.Add("userName", userName); _webClient.Headers.Add("channelId", "*****"); _webClient.Headers.Add("timestamp", timeStamp); _webClient.Headers.Add("userKey", userkey); _webClient.Headers.Add("model", "getPolicyZip"); _webClient.Headers.Add("policyConstraint", "{}"); _webClient.Encoding = Encoding.UTF8; try { //使用UploadFile方法可以用下面的格式 byte[] responseArray = _webClient.UploadFile(url, fileNamePath); string msg = Encoding.GetEncoding("gb2312").GetString(responseArray); } catch (Exception er) { base.error.Ex = er; base.error.Message = "上传失败"; return false; } return true; }
2.HttpWebRequest 上传文件
public string UpLoadFile(string filePath, string url) { string responseData = String.Empty; HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url); FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); byte[] buffur = new byte[fileStream.Length]; fileStream.Read(buffur, 0, (int)fileStream.Length); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = fileStream.Length; string timeStamp = DateTime.Now.ToString("YYYY-MM-DD HH:mm:ss"); string userName = "*****"; string passWord = "*****"; string uniqueKey = "*****"; string userkey = Md5Helper.GetMD5String(userName + passWord + uniqueKey + timeStamp); req.Headers.Add("userName", userName); req.Headers.Add("channelId", "*****"); req.Headers.Add("timestamp", timeStamp); req.Headers.Add("userKey", userkey); req.Headers.Add("model", "getPolicyZip"); req.Headers.Add("policyConstraint", "{}"); Stream reqStream = req.GetRequestStream(); reqStream.Write(buffur, 0, buffur.Length); reqStream.Close(); using (HttpWebResponse response = (HttpWebResponse)req.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("GB2312"))) { responseData = reader.ReadToEnd().ToString(); } return responseData; } }
总结:
关于WebClient和HttpWebRequest的区别 http://www.cnblogs.com/shikyoh/archive/2011/05/04/2036514.html
a)需要注意ContentType的值。
b)需要注意headers每个参数的值,例如其中的'policyConstraint'是json数据,为空的时候应为"{}"。