C#中webclient(http、Request、Response、post、get)在winform中的使用
題外話::04年到07年搞了四年多的C#,突然發現,居然還能撿起來解決客戶的需求,很是欣喜,裝了VS2010,突然又喜歡上了用C#寫東西。前段時間用C#寫了一個通過SAP 呼叫codeproject的中介軟體,最近打算利用業餘時間用C#寫一個SAP與外部系統介面的EDI系統,沒事了,搞著玩玩吧。
最近遇到的需求如下:
需要從SAP中獲取快遞單號,然後根據快遞單號呼叫國外的一個物流公司提供的rest api,只能利用http的get、post傳送或接收json,去操作或獲取遠端REST服務,但是客戶這裡沒有可以使用的IIS,開發出來的ASP.net沒地方部署!突然想出了個辦法:把這些http請求放在winform裡,做一個服務,隨便扔到一臺既可以連線SAP的,又能訪問外網的機器上,就可以定時從SAP輪詢獲取快遞單號,又可以通過呼叫遠端的REST API獲取這些快遞單號的快遞資訊,然後再寫入SAP中,以供使用者在SAP裡查詢這些快遞的快遞資訊。有這樣的想法後,居然實現了,程式碼如下,貼出來,以供需要的兄弟可以參考:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Web;
using SAP.Middleware.Connector;
using System.Threading;
namespace Baba
{
public partial class frmMain : Form
{
private static string _apiKey = " 物流公司提供的APIKEY";
private static string _companyId = "companyId";
private static string _baseUrl = "物流公司RESTAPI URL";
private static string strFlag = "";
private static string strDevIP = "";
private static string strPrdIP = "";
public frmMain()
{
InitializeComponent();
this.Load += new EventHandler(frmMain_Load);
}
class TimerExampleState
{
public int counter = 0;
public System.Threading.Timer tmr;
}
//下面是被定時呼叫的方法
static void CheckStatus(Object state)
{
//TimerExampleState s = (TimerExampleState)state;
//s.counter++;
Upd_KDXX();
//Console.WriteLine("{0} Checking Status {1}.", DateTime.Now.TimeOfDay, s.counter);
//MessageBox.Show("aa");
//if (s.counter == 5)
//{
// //使用Change方法改變了時間間隔
// (s.tmr).Change(10000, 2000);
// //Console.WriteLine("changed");
//}
//if (s.counter == 10)
//{
// //Console.WriteLine("disposing of timer");
// s.tmr.Dispose();
// s.tmr = null;
//}
}
void frmMain_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
try
{
strDevIP = this.txtDevIP.Text.Trim();
strPrdIP = this.txtPrdIP.Text.Trim();
if (radioButton1.Checked == true)
{
strFlag = "1";
if (strDevIP == "")
{
MessageBox.Show("開發機IP不能為空");
return;
}
}
else
{
strFlag = "2";
if (strPrdIP == "")
{
MessageBox.Show("生產機IP不能為空");
return;
}
}
TimerExampleState s = new TimerExampleState();
//建立代理物件TimerCallback,該代理將被定時呼叫
TimerCallback timerDelegate = new TimerCallback(CheckStatus);
if (this.textBox1.Text.ToString() == "")
{
MessageBox.Show("時間間隔不允許為空");
}
else
{
MessageBox.Show("定時器啟用成功,程式會按設定時間間隔執行");
this.txtTip.Text = "定時功能已啟用,若改變設定,請退出程式後重新設定";
this.txtDevIP.Enabled = false;
this.txtPrdIP.Enabled = false;
this.textBox1.Enabled = false;
this.button1.Enabled = false;
this.radioButton1.Enabled = false;
this.radioButton2.Enabled = false;
if (strFlag == "1")
{
this.radioButton1.Checked = true;
}
else
{
this.radioButton2.Checked = true;
}
//建立一個時間間隔為1s的定時器
int isecond;
isecond = Convert.ToInt16(this.textBox1.Text.ToString()) * 1000;
System.Threading.Timer timer = new System.Threading.Timer(timerDelegate, s, isecond, isecond);
s.tmr = timer;
//主執行緒停下來等待Timer物件的終止
//while (s.tmr != null)
// Thread.Sleep(0);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
static void Upd_KDXX()
{
WebClient client = new WebClient(); // Create a new instance of WebClient.
client.Headers.Add(HttpRequestHeader.Authorization, _apiKey); // Add the API key to the Authorization header of the request if the account does not allow anonymous access.
try
{
RfcConfigParameters rfcPar = new RfcConfigParameters();
if (strFlag == "1")
{
rfcPar.Add(RfcConfigParameters.Name, "DEV");
rfcPar.Add(RfcConfigParameters.AppServerHost, strDevIP);
rfcPar.Add(RfcConfigParameters.Client, " client ");
rfcPar.Add(RfcConfigParameters.User, "usname");
rfcPar.Add(RfcConfigParameters.Password, "password");
rfcPar.Add(RfcConfigParameters.SystemNumber, "SAP例項編號");
rfcPar.Add(RfcConfigParameters.Language, "EN");
}
else
{
rfcPar.Add(RfcConfigParameters.Name, "PRD");
rfcPar.Add(RfcConfigParameters.AppServerHost, strPrdIP);
rfcPar.Add(RfcConfigParameters.Client, "client");
rfcPar.Add(RfcConfigParameters.User, "username");
rfcPar.Add(RfcConfigParameters.Password, "password");
rfcPar.Add(RfcConfigParameters.SystemNumber, "SAP例項編號");
rfcPar.Add(RfcConfigParameters.Language, "EN");
}
RfcDestination dest = RfcDestinationManager.GetDestination(rfcPar);
RfcRepository rfcrep = dest.Repository;
IRfcFunction myfun = null;
myfun = rfcrep.CreateFunction("SAP裡RFC函式名");
myfun.Invoke(dest);
IRfcTable IrfTable = myfun.GetTable("OUTPUT");
IRfcFunction myfun1 = null;
myfun1 = rfcrep.CreateFunction("SAP裡RFC函式名");
//myfun1.Invoke(dest);
IRfcTable IrfTable1 = myfun1.GetTable("INPUT");
IrfTable1.Clear();
//迴圈把IRfcTable裡面的資料放入Table裡面,因為型別不同,不可直接使用。
for (int i = 0; i < IrfTable.Count; i++)
{
string strHYNO = IrfTable[i].GetString("HYNO").Trim();
if (strHYNO != "")
{
var orders = JsonConvert.DeserializeObject<Guid[]>(client.DownloadString(_baseUrl + "orders?trackingNumber=" + strHYNO));// Query the API for the ID of an order with the tracking number 4787, and deserialize the JSON response.
if (orders.Length > 0)
{
var order = JObject.Parse(client.DownloadString(_baseUrl + "orders/" + orders[0].ToString())); // Query the API for the order object, and deserialize the JSON response.
if (order != null)
{
Newtonsoft.Json.Linq.JObject jobject = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(order.ToString());
string strReferenceNumber = Convert.ToString(jobject["ReferenceNumber"]);
string[] sArray = strReferenceNumber.Split('/');
string strTrackingNumber = Convert.ToString(jobject["TrackingNumber"]);
string strPoNum = Convert.ToString(sArray[0]);
strPoNum = strPoNum.Replace("PO", "");
string strDeliveryContactName = Convert.ToString(jobject["DeliveryContactName"]);
string strDeliveryArrivalDate = Convert.ToString(jobject["DeliveryArrivalDate"]);
strDeliveryArrivalDate = strDeliveryArrivalDate.Replace("T", " ");
string strCompanyName = Convert.ToString(jobject["DeliveryLocation"]["CompanyName"]);
string strAddressLine1 = Convert.ToString(jobject["DeliveryLocation"]["AddressLine1"]);
string strAddressLine2 = Convert.ToString(jobject["DeliveryLocation"]["AddressLine2"]);
string strCity = Convert.ToString(jobject["DeliveryLocation"]["City"]);
string strState = Convert.ToString(jobject["DeliveryLocation"]["State"]);
string strStatus = Convert.ToString(jobject["Status"]["Description"]);
string strPostalCode = Convert.ToString(jobject["DeliveryLocation"]["PostalCode"]);
//回填相關資訊
IrfTable1.Insert();
IrfTable1.CurrentRow.SetValue("KDDH", strTrackingNumber);
IrfTable1.CurrentRow.SetValue("XH", "1");
IrfTable1.CurrentRow.SetValue("PONUM", strPoNum);
IrfTable1.CurrentRow.SetValue("DCNAME", strDeliveryContactName);
IrfTable1.CurrentRow.SetValue("DADATE", strDeliveryArrivalDate);
IrfTable1.CurrentRow.SetValue("COMNAM", strCompanyName);
IrfTable1.CurrentRow.SetValue("ADDRS1", strAddressLine1);
IrfTable1.CurrentRow.SetValue("ADDRS2", strAddressLine2);
IrfTable1.CurrentRow.SetValue("CITY", strCity);
IrfTable1.CurrentRow.SetValue("STATE", strState);
IrfTable1.CurrentRow.SetValue("STATUS", strStatus);
IrfTable1.CurrentRow.SetValue("POSTALCODE", strPostalCode);
}
}
}
}
if (IrfTable1.Count > 0)
{
//傳遞內表引數,執行RFC
myfun1 = rfcrep.CreateFunction("ZMM_UPD_YDH"); //呼叫函式名
myfun1.SetValue(0, IrfTable1);
myfun1.Invoke(dest);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void frmMain_SizeChanged(object sender, EventArgs e)
{
try
{
if (this.WindowState == FormWindowState.Minimized)
{
this.Hide();
this.notifyIcon.Visible = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void notifyIcon_Click(object sender, EventArgs e)
{
try
{
this.Visible = true;
this.WindowState = FormWindowState.Normal;
this.notifyIcon.Visible = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}