WebService 接收這個部分找了超多資料,搞了三天才搞定
-------以下WebService的程式碼,寫在asmx裡面
using System.Web.Services;
using System.Web.Script.Services;
using System.IO;
using System.Text;
using Newtonsoft.Json.Linq;
namespace WebService
{
[WebService(Namespace = "http://microsoft.com/webservices/")]
public class iWS : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string PostGetData()
{
//應用程式呼叫的網址 : "http://localhost:54756/iWS.asmx/PostGetData"
Stream s = System.Web.HttpContext.Current.Request.InputStream;
byte[] b = new byte[s.Length];
s.Read(b, 0, (int)s.Length);
string aa = Encoding.UTF8.GetString(b);
return aa;
}
}
}
-------以上WebService的程式碼,寫在asmx裡面
-------以下ConsoleApplication,寫在Program.cs裡面
using System;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net;
using System.IO;
using System.Data.SqlClient;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string targetUrl = "http://localhost/iWS.asmx/PostGetData";
string connString = "你資料庫的位置";
byte[] postData;
string jsonStr;
try
{
string strSQL = "SELECT 'H123' as a, " + "\r\n" +
"'56789' as b, " + "\r\n" +
"'2' as c, ";
SqlConnection connSQL = new SqlConnection(connString);
connSQL.Open();
SqlCommand comm = new SqlCommand(strSQL, connSQL);
SqlDataReader dr = comm.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dr.Close();
comm.Dispose();
connSQL.Close();
int dtCount = dt.Rows.Count;
for (int i = 0; i < dtCount; i++)
{
JObject obj = new JObject(
new JProperty("a", dt.Rows[i][0].ToString()),
new JProperty("b", dt.Rows[i][1].ToString()),
new JProperty("c", dt.Rows[i][2].ToString())
);
jsonStr = JsonConvert.SerializeObject(obj, Formatting.Indented);
postData = Encoding.UTF8.GetBytes(jsonStr);
HttpWebRequest request = HttpWebRequest.Create(targetUrl) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 30000;
request.ContentLength = postData.Length;
// 寫入 Post Body Message 資料流
using (Stream st = request.GetRequestStream())
{
st.Write(postData, 0, postData.Length);
Console.WriteLine(jsonStr);
}
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
string result = sr.ReadToEnd();
Console.WriteLine(result);
}
}
}
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
}
}
-------以上ConsoleApplication,寫在Program.cs裡面
參考資料 :
http://www.itread01.com/articles/1478475314.html
https://kknews.cc/zh-tw/other/4egm2v.html
沒有留言:
張貼留言