您好,登錄后才能下訂單哦!
這篇文章主要講解了“C#怎么利用http協議與服務器通信”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“C#怎么利用http協議與服務器通信”吧!
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 HttpWebTool
{
/// <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>
/// <returns>返回請求結果字符串,返回為null代表請求失敗</returns>
public String getDatafromHttpWebServer(String url, Hashtable data,CookieCollection cookies)
{
String result = null;
if (string.IsNullOrEmpty(url))
{
return null;//傳入參數異常
}
byte[] data_stream = null;//將要向服務器傳輸的數據流內容
if (data != null && data.Count > 0)
{
string transportData = "";//將要向服務器傳輸的字符串內容
foreach (DictionaryEntry de in data)
{
transportData = transportData + de.Key.ToString() + "=" + de.Value.ToString() + "&";//解調出鍵值對數據
}
transportData = transportData.TrimEnd('&');//去除字符串尾部的 &
if (!string.IsNullOrEmpty(transportData))
{
data_stream = Encoding.UTF8.GetBytes(transportData);//將上傳字符串數據打包成數據流
}
}
try
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
//請求方式
req.Method = "POST";
//聲明客戶端只接收txt類型的內容
req.Accept = "text/plain";
//以鍵值對形式向服務器傳遞參數
req.ContentType = "application/x-www-form-urlencoded";
//設置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;
if (data_stream != null && data_stream.Length > 0)
{
//請求數據流的長度
req.ContentLength = data_stream.Length;
using (Stream requestStream = req.GetRequestStream()) {
//寫入請求實體流
requestStream.Write(data_stream, 0, data_stream.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;
}
}
}
感謝各位的閱讀,以上就是“C#怎么利用http協議與服務器通信”的內容了,經過本文的學習后,相信大家對C#怎么利用http協議與服務器通信這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。