带图片的post数据请求
2019-04-15 13:47发布
生成海报
///
/// Posts the pics.
///
/// .
/// URL.
/// Pic file name.
/// Pic path list.
/// Parameter.
public string PostPics (string url, string picFileName, List picPathList, Dictionary 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 ("
--" + boundary + "
");
byte[] endBoundaryBytes = Encoding.UTF8.GetBytes ("
--" + boundary + "--
");
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}"
Content-Type:application/octet-stream
", 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}"
{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;
}
打开微信“扫一扫”,打开网页后点击屏幕右上角分享按钮