您好,登錄后才能下訂單哦!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Net;
using System.IO;
namespace www.xinduofen.cn
{
/// <summary>
/// C#與http服務器端進行對接的工具類
/// </summary>
class www.xinduofen.com
{
/// <summary>
/// 用于緩存服務器端傳輸到客戶端的SESSIONID或者JSESSIONID
/// </summary>
private Cookie sessionidCookie = null;
/// <summary>
/// 向HttpWebServer端上傳文件(使用的是"post"方式)
/// </summary>
/// <param name="url">請求網址</param>
/// <param name="data">請求參數集合,無需參數時傳入null值</param>
/// <param name="cookies">請求cookie集合,無需cookie時傳入null值</param>
/// <param name="filesSaveAddress">上傳文件集合《控件名,上傳文件的保存位置(包括"文件名"."擴展名")》,無需上傳時傳入null值</param>
/// <returns>返回請求結果字符串,返回為null代表請求失敗</returns>
public String setFilesToHttpWebServer(String url, Hashtable data, CookieCollection cookies, Hashtable filesSaveAddress)
{
//用于緩存服務器端傳輸回來的結果字符串
string result = null;
if (string.IsNullOrEmpty(url))
{
return null;//傳入參數異常
}
//用于分割信息部分的分隔符(不能與消息原文沖突)
String boundary = "HttpWebTool" + DateTime.Now.Ticks;
//結束分隔符數據流
byte[] andBoundary = Encoding.UTF8.GetBytes("--" + boundary + "--");
//新行字符串數據流
byte[] newline = Encoding.UTF8.GetBytes("\r\n");
try
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
//請求方式
req.Method = "POST";
//聲明客戶端只接收txt類型的內容
req.Accept = "text/plain";
//以消息的形式向服務器傳遞參數和數據流
req.ContentType = "multipart/form-data; boundary=" + boundary;
//設置cookie盒子(客戶端請求的cookie和服務器端返回的cookie就放在此盒子中)
CookieContainer cookieContainer = new CookieContainer();
if (sessionidCookie != null && !string.IsNullOrEmpty(sessionidCookie.Domain))
{
cookieContainer.Add(sessionidCookie);
}
if (cookies != null)
{
cookieContainer.Add(cookies);//添加調用者傳入的cookie集合
}
req.CookieContainer = cookieContainer;
//用于累計數據流長度,初始化為0
long dataCount = 0;
byte[] parameterBytes = getParameterBytes(data, boundary);
if (parameterBytes != null && parameterBytes.Length>0)
{
//累計請求參數字符串數據流大小
dataCount += parameterBytes.Length;
}
//<控件名,上傳文件的消息頭部分字符流byte[]>
Hashtable uploadFileDeclareBytesSet = new Hashtable();
//如果有要上傳的文件
if (filesSaveAddress != null && filesSaveAddress.Count > 0)
{
foreach (DictionaryEntry de in filesSaveAddress)
{
//如果將要上傳的文件存在
if (File.Exists(de.Value.ToString()))
{
byte[] uploadFileDeclareBytes = getUploadFileDeclareBytes(de, boundary);
if (uploadFileDeclareBytes!=null)
{
//累計上傳文件消息頭部描述字符串數據流大小
dataCount += uploadFileDeclareBytes.Length;
//累計上傳文件正文數據流大小
dataCount += new FileInfo(de.Value.ToString()).Length;
//累計新行字符串數據流數據流大小
dataCount += newline.Length;
uploadFileDeclareBytesSet.Add(de.Key.ToString(), uploadFileDeclareBytes);
}
}
}
}
//如果有數據流
if (dataCount>0)
{
//累計結束分隔符數據流大小
dataCount += andBoundary.Length;
//請求數據流的長度
req.ContentLength = dataCount;
using (Stream requestStream = req.GetRequestStream())
{
if (parameterBytes != null && parameterBytes.Length > 0)
{
requestStream.Write(parameterBytes, 0, parameterBytes.Length);
}
if (filesSaveAddress != null && filesSaveAddress.Count > 0)
{
foreach (DictionaryEntry de in filesSaveAddress)
{
if (File.Exists(de.Value.ToString()))
{
byte[] uploadFileDeclareBytes = (byte[])uploadFileDeclareBytesSet[de.Key.ToString()];
requestStream.Write(uploadFileDeclareBytes, 0, uploadFileDeclareBytes.Length);
using (FileStream fileStream = new FileStream(de.Value.ToString(), FileMode.Open, FileAccess.Read))
{
//建立字節組,并設置它的大小是多少字節
byte[] bytes = new byte[10240];
int n = -1;
while ((n = fileStream.Read(bytes, 0, bytes.Length)) > 0)
{
requestStream.Write(bytes, 0, n); //將指定字節的流信息寫入文件流中
}
}
requestStream.Write(newline, 0, newline.Length);
}
}
}
requestStream.Write(andBoundary, 0, andBoundary.Length);
}
}
//接收返回值
using (HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse()) {
using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8)) {
result = reader.ReadToEnd().Trim();
}
if (myResponse.Cookies["SESSIONID"] != null)
{
sessionidCookie = myResponse.Cookies["SESSIONID"];
}
else
{
if (myResponse.Cookies["JSESSIONID"] != null)
{
sessionidCookie = myResponse.Cookies["JSESSIONID"];
}
}
}
}
catch (Exception)
{
Console.WriteLine("請查看傳入參數是否正確或者服務器是否關閉");
}
return result;
}
/// <summary>
/// 獲得參數data的消息數據流,以"\r\n"結尾
/// </summary>
/// <param name="data">請求參數集合,無需參數時傳入null值</param>
/// <param name="boundary">消息分隔符</param>
/// <returns>返回參數data的數據流,返回為空代表獲得失敗</returns>
private byte[] getParameterBytes(Hashtable data, String boundary)
{
byte[] parameterBytes = null;
//如果有請求參數
if (data != null && data.Count > 0)
{
string parameterStr = "";
foreach (DictionaryEntry de in data)
{
parameterStr += "--" + boundary;
parameterStr += "\r\n" + "Content-Disposition: form-data;name=\"" + de.Key.ToString() + "\"";
parameterStr += "\r\n" + "Content-Type: text/plain; charset=UTF-8";
parameterStr += "\r\n\r\n" + de.Value.ToString();
parameterStr += "\r\n";
}
if (!string.IsNullOrEmpty(parameterStr))
{
parameterBytes = Encoding.UTF8.GetBytes(parameterStr);//將上傳字符串數據打包成數據流
}
}
return parameterBytes;
}
/// <summary>
/// 獲得上傳文件的消息頭部分字符流,以"\r\n\r\n"結尾
/// </summary>
/// <param name="de">上傳文件《控件名,上傳文件的保存位置(包括"文件名"."擴展名")》</param>
/// <param name="boundary">消息分隔符</param>
/// <returns>返回上傳文件的消息頭部分字符流,返回會為null代表獲得失敗</returns>
private byte[] getUploadFileDeclareBytes(DictionaryEntry de, String boundary)
{
byte[] uploadFileDeclareBytes = null;
//上傳文件的消息頭描述部分
string uploadFileDeclareStr = "";
uploadFileDeclareStr += "--" + boundary;
uploadFileDeclareStr += "\r\n" + "Content-Disposition: form-data;name=\"" + de.Key.ToString() + "\"; filename=\"" + de.Value.ToString() + "\"";
uploadFileDeclareStr += "\r\n" + "Content-Type: application/octet-stream";
uploadFileDeclareStr += "\r\n\r\n";
if (!string.IsNullOrEmpty(uploadFileDeclareStr))
{
uploadFileDeclareBytes = Encoding.UTF8.GetBytes(uploadFileDeclareStr);//將上傳字符串數據打包成數據流
}
return uploadFileDeclareBytes;
}
}
}
內容所有權屬于越康體育(專業從事體質測試儀,學生體質測試儀的研究)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。