/// <summary>
/// Posts the pics.
/// </summary>
/// <returns>.</returns>
/// <param name="url">URL.</param>
/// <param name="picFileName">Pic file name.</param>
/// <param name="picPathList">Pic path list.</param>
/// <param name="param">Parameter.</param>
public string PostPics (string url, string picFileName, List<string> picPathList, Dictionary<string,string> param)
{
string boundary = "----------------------------" + DateTime.Now.Ticks.ToString ("x");
HttpWebRequest request = WebRequest.Create (url) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "multipart/form-data; boundary=" + boundary;
// 设置参数
request.AllowAutoRedirect = true;
request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes ("\r\n--" + boundary + "\r\n");
byte[] endBoundaryBytes = Encoding.UTF8.GetBytes ("\r\n--" + boundary + "--\r\n");
Stream postStream = request.GetRequestStream ();
postStream.Write (itemBoundaryBytes, 0, itemBoundaryBytes.Length);
//files
for (int i = 0; i < picPathList.Count; i++) {
string FilePath = picPathList [i];
int pos = FilePath.LastIndexOf ("\\");
string fileName = FilePath.Substring (pos + 1);
//请求头部信息
string postDataName = picFileName + "[" + i + "]";
StringBuilder sbHeader = new StringBuilder (string.Format ("Content-Disposition:form-data;name=\"{0}\";filename=\"{1}\"\r\nContent-Type:application/octet-stream\r\n\r\n", postDataName, fileName));
byte[] postHeaderBytes = Encoding.UTF8.GetBytes (sbHeader.ToString ());
FileStream fs = new FileStream (FilePath, FileMode.Open, FileAccess.Read);
byte[] bArr = new byte[fs.Length];
fs.Read (bArr, 0, bArr.Length);
fs.Close ();
//file
postStream.Write (postHeaderBytes, 0, postHeaderBytes.Length);
postStream.Write (bArr, 0, bArr.Length);
postStream.Write (itemBoundaryBytes, 0, itemBoundaryBytes.Length);
}
//key-values
foreach (var a in param) {
Debug.Log (a.Key + ":" + a.Value);
StringBuilder nameHeader = new StringBuilder (string.Format ("Content-Disposition:form-data;name=\"{0}\"\r\n\r\n{1}", a.Key, a.Value));
byte[] bs = Encoding.UTF8.GetBytes (nameHeader.ToString ());
postStream.Write (bs, 0, bs.Length);
postStream.Write (itemBoundaryBytes, 0, itemBoundaryBytes.Length);
}
postStream.Write (endBoundaryBytes, 0, endBoundaryBytes.Length);
postStream.Close ();
//错误处理
StreamReader sr;
HttpStatusCode hs = new HttpStatusCode();
try {
//发送请求并获取相应回应数据
HttpWebResponse response = request.GetResponse () as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
Stream instream = response.GetResponseStream ();
hs = response.StatusCode;
sr = new StreamReader (instream, Encoding.UTF8);
} catch (WebException ex) {
Stream responseStream = ex.Response.GetResponseStream ();
sr = new StreamReader (responseStream, Encoding.UTF8);
}
//返回结果网页(html)代码
string content = sr.ReadToEnd ();
Debug.Log (content);
Debug.Log("ylj="+ hs.ToString());
return content;
}
带图片的post数据请求
最新推荐文章于 2021-03-13 22:50:23 发布