璽瑞(SYRIS)_C#(VS2015/.net 4.X) HTTPS 通訊程式 模組
璽瑞(SYRIS)_C#(VS2015/.net 4.X) HTTPS 通訊程式 模組
資料來源:
https://github.com/jash-git/CS-Reading-REST-API-chunked
https://github.com/jash-git/CS_WebClient_TLS_Download
https://github.com/jash-git/CS_wait_PHP
01.允許https證書不進行網路認證模塊 (主程式必須引入和執行)
//---
//把API呼叫換成支援https模式
public bool ValidateServerCertificate(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
public void CS_https_tls_setting()
{
//REF: https://stackoverflow.com/a/39534068/288936
ServicePointManager.SecurityProtocol =
SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls |
SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
//REF: https://docs.microsoft.com/zh-tw/dotnet/api/system.net.servicepointmanager.expect100continue?view=netframework-4.7.2
//REF: https://www.cnblogs.com/dudu/p/the_remote_certificate_is_invalid_according_to_the_validation_procedure.html
ServicePointManager.UseNagleAlgorithm = true;
ServicePointManager.Expect100Continue = true;
ServicePointManager.CheckCertificateRevocationList = false;//The remote certificate is invalid according to the validation procedure
ServicePointManager.DefaultConnectionLimit = ServicePointManager.DefaultPersistentConnectionLimit;
//REF: http://libraclark.blogspot.com/2007/06/ssl.html
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
}
//---把API呼叫換成支援https模式
02.cloud API 通訊
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;
using System.IO;
using System.Net.Cache;
using System.Threading;
using System.Windows.Forms;
using System.Collections;
namespace SYWEB_V8_Workstation
{
public class CS2PHPrestfulapi
{
public static bool m_blnReadOneLine = false;//授權改成有收到回應就離開
public static string [] m_StrChunkedNewData;
public static string [] m_StrChunkedOldData;
//把TIMER在做資料存放到FIFO的工作移至執行緒中,確保資料的完整性 public static string [] m_StrCardEventData;
public static Thread [] m_ThreadChunked;
public static string[] m_StrSYDMVar;
public const int m_intCardEventSize = 200;
public static String[] m_StrCardEventShowData = new String[m_intCardEventSize];//把TIMER在做資料存放到FIFO的工作移至執行緒中,確保資料的完整性
public static bool m_blnNewChunked00 = false;// 修正即時監控和有源標籤監測的清掉資料判斷機制
public const int m_intActiveRFIDSize = 5000;
public static String[] m_StrActiveRFIDShowData = new String[m_intActiveRFIDSize];//把TIMER在做資料存放到FIFO的工作移至執行緒中,確保資料的完整性
public static bool m_blnNewChunked01 = false;// 修正即時監控和有源標籤監測的清掉資料判斷機制
public static int m_intCountChunked = 0;
public static String m_StrX_GAPI_Token = "";//X-GAPI-Token
public static String m_StrX_GAPI_Signature = "";//X-GAPI-Signature
public static String m_StrX_GAPI_Countersign = "";//X-GAPI-Countersign
public static void setHttpGAPIHeader(ref HttpWebRequest request)
{
if (m_StrX_GAPI_Token.Length>0)
{
request.Headers["X-GAPI-Token"] = m_StrX_GAPI_Token;
}
if (m_StrX_GAPI_Signature.Length > 0)
{
request.Headers["X-GAPI-Signature"] = m_StrX_GAPI_Signature;
}
if (m_StrX_GAPI_Countersign.Length > 0)
{
request.Headers["X-GAPI-Countersign"] = m_StrX_GAPI_Countersign;
}
}
public static void shiftCardEventDataArray(String StrData)//把TIMER在做資料存放到FIFO的工作移至執行緒中,確保資料的完整性
{
FileLib.logFile("CardEventShowRawData.txt", StrData);//建立正確時的即時訊息Raw Data LOG
for (int i = (m_StrCardEventShowData.Length - 2); i >= 0; i--)
{
m_StrCardEventShowData[i + 1] = m_StrCardEventShowData[i];
}
m_StrCardEventShowData[0] = StrData;
m_blnNewChunked00 = true;//修正即時監控和有源標籤監測的清掉資料判斷機制
m_intCountChunked++;
}
public static void shiftActiveRFIDDataArray(String StrData)//把TIMER在做資料存放到FIFO的工作移至執行緒中,確保資料的完整性
{
FileLib.logFile("ActiveRFIDShowRawData.txt", StrData);//建立正確時的即時訊息Raw Data LOG
for (int i = (m_StrActiveRFIDShowData.Length - 2); i >= 0; i--)
{
m_StrActiveRFIDShowData[i + 1] = m_StrActiveRFIDShowData[i];
}
m_StrActiveRFIDShowData[0] = StrData;
m_blnNewChunked01 = true;//修正即時監控和有源標籤監測的清掉資料判斷機制
m_intCountChunked++;
}
public static void Thread_funGet(object arg)//新增接收chunked執行序主體函數
{
String StrData = (String)arg;
string[] strs = StrData.Split('$');
RESTfulAPI_getchunked(strs[0], strs[1], Convert.ToInt32(strs[2]));
}
public static void RESTfulAPI_getchunked(String url, String data, int index)//新增專用POST模式下的chunked函數
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
setHttpGAPIHeader(ref request);
//--
//定義此req的緩存策略
//https://msdn.microsoft.com/zh-tw/library/system.net.webrequest.cachepolicy(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1
HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
request.CachePolicy = noCachePolicy;
//--
request.Method = "GET";
request.ContentType = "application/json; charset=UTF-8";//POST to AJAX [is_ajax_request()]
Thread.Sleep(100);
System.Net.ServicePointManager.DefaultConnectionLimit = 200;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默认编码
}
//---
//add 2017/12/20
//Reading “chunked” response with HttpWebResponse - https://stackoverflow.com/questions/16998/reading-chunked-response-with-httpwebresponse
StringBuilder sb = new StringBuilder();
Byte[] buf = new byte[8192];
Stream resStream = response.GetResponseStream();
string tmpString = null;
int count = 0;
do
{
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
tmpString = Encoding.UTF8.GetString(buf, 0, count);
FileLib.logFile("EventGetRawData.txt", tmpString);//建立收到資料第一時間的即時訊息Raw Data LOG
m_StrChunkedNewData[index] = tmpString;
if (m_StrChunkedNewData[index] != m_StrChunkedOldData[index])
{
m_StrChunkedOldData[index] = m_StrChunkedNewData[index];
//---
//修改即時監控,當一次收到多筆時也要能拆解資料並顯示而非判定為不能解析資料
string[] lines = m_StrChunkedNewData[index].Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);//修改即時監控,當一次收到多筆時也要能拆解資料並顯示而非判定為不能解析資料~
for (int i = 0; i < lines.Length; i++)
{
if (lines[i].Contains("\"type\":5"))
{
//---
//JSON2OBJ
try
{
V092_ActiveRFIDLog ARLBuf = null;
ARLBuf = parseJSON.parseV092_ActiveRFIDLog(lines[i]);
//---
//過濾
bool blnshowData = false;
blnshowData = true;
if (blnshowData == true)
{
shiftActiveRFIDDataArray(lines[i]);
}
//---過濾
}
catch
{
FileLib.logFile("EventErrorRawData.txt", lines[i]);//修改即時監控,當一次收到多筆時也要能拆解資料並顯示而非判定為不能解析資料~ FileLib.logFile("CardEventErrorRawData.txt", m_StrChunkedNewData[index]);//建立錯誤時的即時訊息Raw Data LOG
}
//---JSON2OBJ
}
if (lines[i].Contains("\"type\":4"))//修改即時監控,當一次收到多筆時也要能拆解資料並顯示而非判定為不能解析資料~ if (m_StrChunkedNewData[index].Contains("\"type\":4"))
{
//---
//JSON2OBJ
try
{
V09_CardEventlog CELBuf = null;
CELBuf = parseJSON.parseV09_CardEventlog(lines[i]);//修改即時監控,當一次收到多筆時也要能拆解資料並顯示而非判定為不能解析資料~ CELBuf = parseJSON.parseV09_CardEventlog(m_StrChunkedNewData[index]);
//---
//即時監控UI的過濾條件判斷機制搬到執行序執行
bool blnshowData = false;
int intsate = -1;
int intid = -1;
int intsn = -1;
for (int x = 0; x < Main_Frm.pForm1.m_ALCardEventState.Count; x++)
{
intsate = Convert.ToInt32(Main_Frm.pForm1.m_ALCardEventState[x].ToString());
for (int y = 0; y < Main_Frm.pForm1.m_ALCardEventDoor.Count; y++)
{
string[] strs = Main_Frm.pForm1.m_ALCardEventDoor[y].ToString().Split(',');
intid = Convert.ToInt32(strs[0]);
intsn = Convert.ToInt32(strs[1]);
if ((CELBuf.status == intsate) && (CELBuf.controller_door_index == intid) && (CELBuf.controller_serial_number == intsn))
{
blnshowData = true;
break;
}
}
if (blnshowData == true)
{
break;
}
}
if (blnshowData == true)
{
shiftCardEventDataArray(lines[i]);//修改即時監控,當一次收到多筆時也要能拆解資料並顯示而非判定為不能解析資料~ shiftCardEventDataArray(m_StrChunkedNewData[index]);//把TIMER在做資料存放到FIFO的工作移至執行緒中,確保資料的完整性
}
//---即時監控UI的過濾條件判斷機制搬到執行序執行
}
catch
{
FileLib.logFile("EventErrorRawData.txt", lines[i]);//修改即時監控,當一次收到多筆時也要能拆解資料並顯示而非判定為不能解析資料~ FileLib.logFile("CardEventErrorRawData.txt", m_StrChunkedNewData[index]);//建立錯誤時的即時訊息Raw Data LOG
}
//---JSON2OBJ
}
}
//---修改即時監控,當一次收到多筆時也要能拆解資料並顯示而非判定為不能解析資料
}
}
Thread.Sleep(10);
} while (count >= 0);
response.Close();
//---
//手動強制執行當呼叫完 CG API 的強制關閉連線補強措施
request.Abort();
response = null;
request = null;
GC.Collect();//手動記憶體回收
//---手動強制執行當呼叫完 CG API 的強制關閉連線補強措施
}
catch
{
}
}
public static void Thread_funPost(object arg)//新增接收chunked執行序主體函數
{
String StrData = (String)arg;
string[] strs = StrData.Split('$');
RESTfulAPI_postchunked(strs[0], strs[1], Convert.ToInt32(strs[2]));
}
public static void RESTfulAPI_postchunked(String url, String data, int index)//新增專用POST模式下的chunked函數
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
setHttpGAPIHeader(ref request);
//--
//定義此req的緩存策略
//https://msdn.microsoft.com/zh-tw/library/system.net.webrequest.cachepolicy(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1
HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
request.CachePolicy = noCachePolicy;
//--
request.Method = "POST";
//--
//request.ContentType = "application/x-www-form-urlencoded";//一般POST
request.ContentType = "application/json; charset=UTF-8";//POST to AJAX [is_ajax_request()]
//request.Accept = "application/json, text/javascript";//POST to AJAX [is_ajax_request()]
//request.UserAgent = "";//POST to AJAX [is_ajax_request()]
//request.Headers.Add("X-Requested-With", "XMLHttpRequest");//POST to AJAX [is_ajax_request()]
//--
//request.ContentLength = data1.Length;
//StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);//CS2PHPrestfulapi 傳送全部改為UTF8
//writer.Write(data1);
//writer.Flush();
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(data);
streamWriter.Flush();
}
Thread.Sleep(100);
System.Net.ServicePointManager.DefaultConnectionLimit = 200;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默认编码
}
//---
//add 2017/12/20
//Reading “chunked” response with HttpWebResponse - https://stackoverflow.com/questions/16998/reading-chunked-response-with-httpwebresponse
StringBuilder sb = new StringBuilder();
Byte[] buf = new byte[8192];
Stream resStream = response.GetResponseStream();
string tmpString = null;
int count = 0;
do
{
count = resStream.Read(buf, 0, buf.Length);
/*
if (count != 0)
{
tmpString = Encoding.UTF8.GetString(buf, 0, count);
m_StrNewData[index] = tmpString;
}
*/
if (count != 0)
{
tmpString = Encoding.UTF8.GetString(buf, 0, count);
FileLib.logFile("EventGetRawData.txt", tmpString);//建立收到資料第一時間的即時訊息Raw Data LOG
m_StrChunkedNewData[index] = tmpString;
if (m_StrChunkedNewData[index] != m_StrChunkedOldData[index])
{
m_StrChunkedOldData[index] = m_StrChunkedNewData[index];
if (m_StrChunkedNewData[index].Contains("\"type\":4"))
{
//---
//JSON2OBJ
try
{
CardEventlog CELBuf = null;
CELBuf = parseJSON.parseSYCG_CardEventLog(m_StrChunkedNewData[index]);
//---
//即時監控UI的過濾條件判斷機制搬到執行序執行
bool blnshowData = false;
int intsate = -1;
int intid = -1;
int intsn = -1;
for (int x = 0; x < Main_Frm.pForm1.m_ALCardEventState.Count; x++)
{
intsate = Convert.ToInt32(Main_Frm.pForm1.m_ALCardEventState[x].ToString());
for (int y = 0; y < Main_Frm.pForm1.m_ALCardEventDoor.Count; y++)
{
string[] strs = Main_Frm.pForm1.m_ALCardEventDoor[y].ToString().Split(',');
intid = Convert.ToInt32(strs[0]);
intsn = Convert.ToInt32(strs[1]);
if ((CELBuf.message.status == intsate) && (CELBuf.message.controller_door_index == intid) && (CELBuf.message.controller_serial_number == intsn))
{
blnshowData = true;
break;
}
}
if (blnshowData == true)
{
break;
}
}
if (blnshowData == true)
{
shiftCardEventDataArray(m_StrChunkedNewData[index]);//把TIMER在做資料存放到FIFO的工作移至執行緒中,確保資料的完整性
}
//---即時監控UI的過濾條件判斷機制搬到執行序執行
}
catch
{
FileLib.logFile("EventErrorRawData.txt", m_StrChunkedNewData[index]);//建立錯誤時的即時訊息Raw Data LOG
}
//---JSON2OBJ
}
}
}
Thread.Sleep(10);
} while (count >= 0);
response.Close();
//---
//手動強制執行當呼叫完 CG API 的強制關閉連線補強措施
request.Abort();
response = null;
request = null;
GC.Collect();//手動記憶體回收
//---手動強制執行當呼叫完 CG API 的強制關閉連線補強措施
}
catch
{
}
}
public static void RESTfulAPI_getchunked(String url,int index)//新增GET模式下的chunked函數
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
setHttpGAPIHeader(ref request);
//request.SendChunked = true;
//--
//定義此req的緩存策略
//https://msdn.microsoft.com/zh-tw/library/system.net.webrequest.cachepolicy(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1
HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
request.CachePolicy = noCachePolicy;
//--
request.Method = "GET";//request.Method = "POST";
//request.ContentType = "application/x-www-form-urlencoded";
Thread.Sleep(100);
System.Net.ServicePointManager.DefaultConnectionLimit = 200;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //預設編碼
}
//---
//add 2017/12/20
//Reading “chunked” response with HttpWebResponse - https://stackoverflow.com/questions/16998/reading-chunked-response-with-httpwebresponse
StringBuilder sb = new StringBuilder();
Byte[] buf = new byte[8192];
Stream resStream = response.GetResponseStream();
string tmpString = null;
int count = 0;
do
{
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
tmpString = Encoding.UTF8.GetString(buf, 0, count);
m_StrChunkedNewData[index] = tmpString;
if (m_StrChunkedNewData[index] != m_StrChunkedOldData[index])
{
m_StrChunkedOldData[index] = m_StrChunkedNewData[index];
}
}
Thread.Sleep(10);
} while (count >= 0);
response.Close();
//---
//手動強制執行當呼叫完 CG API 的強制關閉連線補強措施
request.Abort();
response = null;
request = null;
GC.Collect();//手動記憶體回收
//---手動強制執行當呼叫完 CG API 的強制關閉連線補強措施
}
catch
{
}
}
public static String RESTfulAPI_get(String url)
{
//string url= "http://192.168.1.68:24410/syris/sydm/controller";
String StrData="";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
setHttpGAPIHeader(ref request);
request.KeepAlive = false;
//--
//定義此req的緩存策略
//https://msdn.microsoft.com/zh-tw/library/system.net.webrequest.cachepolicy(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1
HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
request.CachePolicy = noCachePolicy;
//--
request.Method = "GET";//request.Method = "POST";
//request.ContentType = "application/x-www-form-urlencoded";
Thread.Sleep(100);
System.Net.ServicePointManager.DefaultConnectionLimit = 200;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //預設編碼
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
StrData = reader.ReadToEnd();
//---
//修正當SYCG沒插KEY時雖然API會有回應,但是回應內容會是亂碼非JSON格式,導致系統死當問題
if (StrData.Substring(0, 1) != "{" && StrData.Substring(StrData.Length-1, 1) != "}")
{
StrData = "{\"Ans\":\"Error\"}";
MessageBox.Show(Language.m_StrAPIMsg01, Language.m_StrAPIMsg00, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//---修正當SYCG沒插KEY時雖然API會有回應,但是回應內容會是亂碼非JSON格式,導致系統死當問題
response.Close();
//---
//手動強制執行當呼叫完 CG API 的強制關閉連線補強措施
request.Abort();
response = null;
request = null;
GC.Collect();//手動記憶體回收
//---手動強制執行當呼叫完 CG API 的強制關閉連線補強措施
}
catch (Exception e)
{
StrData = "{\"Ans\":\"Error\"}";
StrData += e.Message;
}
if (SYCGV098.m_blnlogfile)//記錄所有V09_API呼叫log
{
FileLib.logFile(DateTime.Now.ToString("yyyyMMdd") + ".log", SYCGV098.m_StrAPIName + ":" + url + ";" + StrData);
}
return StrData;
}
public static String RESTfulAPI_postBody(String url, String data1, bool blnchunked=false)
{
String data = "";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
setHttpGAPIHeader(ref request);
request.KeepAlive = false;
//--
//定義此req的緩存策略
//https://msdn.microsoft.com/zh-tw/library/system.net.webrequest.cachepolicy(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1
HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
request.CachePolicy = noCachePolicy;
//--
request.Method = "POST";
//--
//request.ContentType = "application/x-www-form-urlencoded";//一般POST
request.ContentType = "application/json; charset=UTF-8";//POST to AJAX [is_ajax_request()]
//request.Accept = "application/json, text/javascript";//POST to AJAX [is_ajax_request()]
//request.UserAgent = "";//POST to AJAX [is_ajax_request()]
//request.Headers.Add("X-Requested-With", "XMLHttpRequest");//POST to AJAX [is_ajax_request()]
//--
//request.ContentLength = data1.Length;
//StreamWriter writer = new StreamWriter(request.GetRequestStream());//CS2PHPrestfulapi 傳送全部改為UTF8
//writer.Write(data1);
//writer.Flush();
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(data1);
streamWriter.Flush();
}
Thread.Sleep(100);
System.Net.ServicePointManager.DefaultConnectionLimit = 200;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默认编码
}
if (!blnchunked)
{
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
//---
//授權改成有收到回應就離開
//data = reader.ReadToEnd();
if (!m_blnReadOneLine)
{
data = reader.ReadToEnd();
}
else
{
data = reader.ReadLine();
data += "\n{\"result\":0}";
m_blnReadOneLine = false;
}
//---授權改成有收到回應就離開
}
else
{
//---
//add 2017/12/20
//Reading “chunked” response with HttpWebResponse - https://stackoverflow.com/questions/16998/reading-chunked-response-with-httpwebresponse
StringBuilder sb = new StringBuilder();
Byte[] buf = new byte[8192];
Stream resStream = response.GetResponseStream();
string tmpString = null;
int count = 0;
do
{
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
tmpString = Encoding.UTF8.GetString(buf, 0, count);
sb.Append(tmpString);
}
Thread.Sleep(10);
} while (count > 0);
data = sb.ToString();
//--
}
//---
//修正當SYCG沒插KEY時雖然API會有回應,但是回應內容會是亂碼非JSON格式,導致系統死當問題
if (data.Substring(0, 1) != "{" && data.Substring(data.Length-1, 1) != "}")
{
data = "{\"Ans\":\"Error\"}";
MessageBox.Show(Language.m_StrAPIMsg01, Language.m_StrAPIMsg00, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//---修正當SYCG沒插KEY時雖然API會有回應,但是回應內容會是亂碼非JSON格式,導致系統死當問題
response.Close();
//---
//手動強制執行當呼叫完 CG API 的強制關閉連線補強措施
request.Abort();
response = null;
request = null;
GC.Collect();//手動記憶體回收
//---手動強制執行當呼叫完 CG API 的強制關閉連線補強措施
}
catch (Exception e)
{
data = "{\"Ans\":\"Error\"}";
data += e.Message;
}
if (SYCGV098.m_blnlogfile)//記錄所有V09_API呼叫log
{
FileLib.logFile(DateTime.Now.ToString("yyyyMMdd") + ".log", SYCGV098.m_StrAPIName + ":" + data1 + ";" + data);
}
return data;
}
public static String RESTfulAPI_putBody(String url, String data1)
{
String data;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
setHttpGAPIHeader(ref request);
request.KeepAlive = false;
//--
//定義此req的緩存策略
//https://msdn.microsoft.com/zh-tw/library/system.net.webrequest.cachepolicy(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1
HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
request.CachePolicy = noCachePolicy;
//--
request.Method = "PUT";
//--
//request.ContentType = "application/x-www-form-urlencoded";//一般POST
request.ContentType = "application/json; charset=UTF-8";//POST to AJAX [is_ajax_request()]
//request.Accept = "application/json, text/javascript";//POST to AJAX [is_ajax_request()]
//request.UserAgent = "";//POST to AJAX [is_ajax_request()]
//request.Headers.Add("X-Requested-With", "XMLHttpRequest");//POST to AJAX [is_ajax_request()]
//--
//---
//修改 HTTP PUT 寫入HEADER資訊
int myStringCount = 0;
int intAddCount = 0;
for (int i = 0; i < data1.Length; i++)
{
byte[] tIntByte = Encoding.Default.GetBytes(data1.Substring(i, 1));
// 中文字
if (tIntByte.Length == 2)
{
//To Do Something
intAddCount++;
}
myStringCount += tIntByte.Length;
}
if(myStringCount!= data1.Length)
{
request.ContentLength = myStringCount + intAddCount;
}
else
{
request.ContentLength = myStringCount;
}
StreamWriter writer = new StreamWriter(request.GetRequestStream());//CS2PHPrestfulapi 傳送全部改為UTF8
writer.Write(data1);
writer.Flush();
/*
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(data1);
streamWriter.Flush();
}
*/
//---修改 HTTP PUT 寫入HEADER資訊
Thread.Sleep(100);
System.Net.ServicePointManager.DefaultConnectionLimit = 200;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默认编码
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
data = reader.ReadToEnd();
//---
//修正當SYCG沒插KEY時雖然API會有回應,但是回應內容會是亂碼非JSON格式,導致系統死當問題
if (data.Substring(0, 1) != "{" && data.Substring(data.Length - 1, 1) != "}")
{
data = "{\"Ans\":\"Error\"}";
MessageBox.Show(Language.m_StrAPIMsg01, Language.m_StrAPIMsg00, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//---修正當SYCG沒插KEY時雖然API會有回應,但是回應內容會是亂碼非JSON格式,導致系統死當問題
response.Close();
//---
//手動強制執行當呼叫完 CG API 的強制關閉連線補強措施
request.Abort();
response = null;
request = null;
GC.Collect();//手動記憶體回收
//---手動強制執行當呼叫完 CG API 的強制關閉連線補強措施
}
catch (Exception e)
{
data = "{\"Ans\":\"Error\"}";
data += e.Message;
}
if (SYCGV098.m_blnlogfile)//記錄所有V09_API呼叫log
{
FileLib.logFile(DateTime.Now.ToString("yyyyMMdd") + ".log", SYCGV098.m_StrAPIName + ":" + data1 + ";" + data);
}
return data;
}
public static String RESTfulAPI_delBody(String url, String data1)
{
String data;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
setHttpGAPIHeader(ref request);
request.KeepAlive = false;
//--
//定義此req的緩存策略
//https://msdn.microsoft.com/zh-tw/library/system.net.webrequest.cachepolicy(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1
HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
request.CachePolicy = noCachePolicy;
//--
request.Method = "DELETE";
//--
//request.ContentType = "application/x-www-form-urlencoded";//一般POST
request.ContentType = "application/json; charset=UTF-8";//POST to AJAX [is_ajax_request()]
//request.Accept = "application/json, text/javascript";//POST to AJAX [is_ajax_request()]
//request.UserAgent = "";//POST to AJAX [is_ajax_request()]
//request.Headers.Add("X-Requested-With", "XMLHttpRequest");//POST to AJAX [is_ajax_request()]
//--
//request.ContentLength = data1.Length;
//StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);//CS2PHPrestfulapi 傳送全部改為UTF8
//writer.Write(data1);
//writer.Flush();
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(data1);
streamWriter.Flush();
}
Thread.Sleep(100);
System.Net.ServicePointManager.DefaultConnectionLimit = 200;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默认编码
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
data = reader.ReadToEnd();
//---
//修正當SYCG沒插KEY時雖然API會有回應,但是回應內容會是亂碼非JSON格式,導致系統死當問題
if (data.Substring(0, 1) != "{" && data.Substring(data.Length-1, 1) != "}")
{
data = "{\"Ans\":\"Error\"}";
MessageBox.Show(Language.m_StrAPIMsg01, Language.m_StrAPIMsg00, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//---修正當SYCG沒插KEY時雖然API會有回應,但是回應內容會是亂碼非JSON格式,導致系統死當問題
response.Close();
//---
//手動強制執行當呼叫完 CG API 的強制關閉連線補強措施
request.Abort();
response = null;
request = null;
GC.Collect();//手動記憶體回收
//---手動強制執行當呼叫完 CG API 的強制關閉連線補強措施
}
catch (Exception e)
{
data = "{\"Ans\":\"Error\"}";
data += e.Message;
}
if (SYCGV098.m_blnlogfile)//記錄所有V09_API呼叫log
{
FileLib.logFile(DateTime.Now.ToString("yyyyMMdd") + ".log", SYCGV098.m_StrAPIName + ":" + data1 + ";" + data);
}
return data;
}
}
}
03.PHP API
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
/*
//http://www.myhow2.net/wp/2012/09/c-visual-studio-2010%E4%B8%AD%E6%B2%A1%E4%BB%80%E4%B9%88%E6%89%BE%E4%B8%8D%E5%88%B0httputility-urlencode%E6%96%B9%E6%B3%95/
原因:Visual Studio 2010中建立的新项目,默认的编译目标平台是”.NET Framework 4.0 Client Profile”, 这个配置没有包含System.Web assembly
解决方法:把编译目标平台改成“.NET Framework 4.0”,然后到Reference里把System.Web Assembly 添加上。
Project -> Properties -> Application -> Target Framework
*/
using System.Web;
using System.Net;
using System.IO;//CookieContainer
namespace SYWEB_V8_Workstation
{
public class CS_PHP
{
public String m_StrDomain;
public String m_StrUsername;
public String m_StrPassword;
public String m_StrResponse;
private CookieContainer m_CookieContainer;
public CS_PHP()
{
m_StrDomain = "http://192.168.1.78:81/";//m_StrDomain = "http://localhost:8080/cs2php/";
m_StrUsername = "admin";
m_StrPassword = "admin";
m_StrResponse = "";
m_CookieContainer = new CookieContainer();
}
public String loginPHP(String PHPName, String StrUserName,bool blnALLData=false)
{
string url = m_StrDomain + PHPName;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
//--
//request.ContentType = "application/x-www-form-urlencoded";//一般POST
request.ContentType = "application/json; charset=UTF-8";//POST to AJAX [is_ajax_request()]
request.Accept = "application/json, text/javascript";//POST to AJAX [is_ajax_request()]
request.UserAgent = "";//POST to AJAX [is_ajax_request()]
request.Headers.Add("X-Requested-With", "XMLHttpRequest");//POST to AJAX [is_ajax_request()]
//--
request.CookieContainer = m_CookieContainer;
//--
//string data = "username=" + HttpUtility.UrlEncode(user) + "&password=" + HttpUtility.UrlEncode(pass);//一般POST
string data = String.Format("\"account\":\"{0}\"", StrUserName);//POST to AJAX [is_ajax_request()]
if (blnALLData == false)
{
data = "{" + data + "}";//POST to AJAX [is_ajax_request()]
}
else
{
data = StrUserName;
}
//--
request.ContentLength = data.Length;
try
{
StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
writer.Write(data);
writer.Flush();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默认编码
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
data = reader.ReadToEnd();
m_CookieContainer = request.CookieContainer;
response.Close();
}
catch
{
data = "{\"result\":false}";
}
/*
//檢查Cookies用
var uri = new Uri(url);
foreach (var cookie in m_CookieContainer.GetCookies(uri))
{
String Data=cookie.ToString(); // test=testValue
}
//*/
return data;
}
public String loginPHP(String PHPName, String StrUserName, String StrPassword)
{
string url = m_StrDomain + PHPName;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
//--
//request.ContentType = "application/x-www-form-urlencoded";//一般POST
request.ContentType = "application/json; charset=UTF-8";//POST to AJAX [is_ajax_request()]
request.Accept = "application/json, text/javascript";//POST to AJAX [is_ajax_request()]
request.UserAgent = "";//POST to AJAX [is_ajax_request()]
request.Headers.Add("X-Requested-With", "XMLHttpRequest");//POST to AJAX [is_ajax_request()]
//--
request.CookieContainer = m_CookieContainer;
string user = StrUserName; //用户名
string pass = StrPassword; //密码
//--
//string data = "username=" + HttpUtility.UrlEncode(user) + "&password=" + HttpUtility.UrlEncode(pass);//一般POST
string data = String.Format("\"account\":\"{0}\", \"password\":\"{1}\"", StrUserName, StrPassword);//POST to AJAX [is_ajax_request()]
data = "{" + data + "}";//POST to AJAX [is_ajax_request()]
//--
request.ContentLength = data.Length;
StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
writer.Write(data);
writer.Flush();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默认编码
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
data = reader.ReadToEnd();
m_CookieContainer = request.CookieContainer;
response.Close();
return data;
}
public String runPHP(String PHPName)
{
string url = m_StrDomain + PHPName;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
//request.ContentType = "application/x-www-form-urlencoded";//一般POST
request.ContentType = "application/json; charset=UTF-8";//POST to AJAX [is_ajax_request()]
request.Accept = "application/json, text/javascript";//POST to AJAX [is_ajax_request()]
request.UserAgent = "";//POST to AJAX [is_ajax_request()]
request.Headers.Add("X-Requested-With", "XMLHttpRequest");//POST to AJAX [is_ajax_request()]
request.CookieContainer = m_CookieContainer;
string data;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默认编码
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
data = reader.ReadToEnd();
m_CookieContainer = request.CookieContainer;
response.Close();
return data;
}
public String runPHP(String PHPName, string StrData)//POST to AJAX [is_ajax_request()]
{
string url = m_StrDomain + PHPName;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
//request.ContentType = "application/x-www-form-urlencoded";//一般POST
request.ContentType = "application/json; charset=UTF-8";//POST to AJAX [is_ajax_request()]
request.Accept = "application/json, text/javascript";//POST to AJAX [is_ajax_request()]
request.UserAgent = "";//POST to AJAX [is_ajax_request()]
request.Headers.Add("X-Requested-With", "XMLHttpRequest");//POST to AJAX [is_ajax_request()]
request.CookieContainer = m_CookieContainer;
string data;
data = StrData;
byte[] bytes = Encoding.UTF8.GetBytes(data);//http://blog.csdn.net/jiankunking/article/details/17992705
request.ContentLength = bytes.Length;
try
{
Stream reqStream = request.GetRequestStream();
reqStream.Write(bytes, 0, bytes.Length);
reqStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默认编码
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
data = reader.ReadToEnd();
m_CookieContainer = request.CookieContainer;
response.Close();
}
catch
{
data = "{\"result\":false}";
}
return data;
}
/*
public String runPHP(String PHPName, String StrData, bool blnRAW = false)//傳統HTTP POST傳送資料
{
string url = m_StrDomain + PHPName;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = m_CookieContainer;
string data = "";
if (!blnRAW)
{
data = "data=" + HttpUtility.UrlEncode(StrData);//vs $_POST['data'];
}
else
{
data = HttpUtility.UrlEncode(StrData);//vs file_get_contents("php://input");
}
request.ContentLength = data.Length;
StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
writer.Write(data);
writer.Flush();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默认编码
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
data = reader.ReadToEnd();
m_CookieContainer = request.CookieContainer;
response.Close();
return data;
}
*/
}
}