C# 利用JsonConvert元件和TcpClient元件實現和非正規HTTP SERVER 用POST+JSON 溝通
C# 利用JsonConvert元件和TcpClient元件實現和非正規HTTP SERVER 用POST+JSON 溝通
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using System.Net;
using System.IO;
using System.Net.Sockets;
namespace CS_Console_login_logout_test
{
public class Login
{
public string model;
public string action;
public LoginUserPassword datagram = new LoginUserPassword();
}
public class LoginUserPassword
{
public string username;
public string password;
}
public class responseLogin_datagram
{
public string api_key;
}
public class responseLogin
{
public string result;
public string error;
public responseLogin_datagram datagram = new responseLogin_datagram();
}
class Program
{
static void Pause()
{
Console.Write(“Press any key to continue . . . “);
Console.ReadKey(true);
}
static void Main(string[] args)
{
//–產生Login資料
Login m_Login = new Login();
m_Login.model = “system”;
m_Login.action = “login”;
m_Login.datagram.username = “admin”;
m_Login.datagram.password = “admin”;
string output = JsonConvert.SerializeObject(m_Login);
Console.WriteLine(output);
try
{
String LOG = “Requesting..”;
TcpClient client = new TcpClient(“192.168.1.123”, 24410);
NetworkStream stream = client.GetStream();
List<string> HEADER = new List<string>();
HEADER.Add(“POST / HTTP/1.0”);
HEADER.Add(“Host:” + “192.168.1.123”);
HEADER.Add(“Content-Type:” + “application/json;charset=UTF-8”);
HEADER.Add(“Content-Length:” + output.Length);
string dataToSend = “”;
for (int h = 0; h < HEADER.Count; h++)
{
dataToSend = dataToSend + HEADER[h] + “\r\n”;
}
dataToSend = dataToSend + “\r\n”;
dataToSend = dataToSend + output + “\r\n”;
byte[] send = Encoding.ASCII.GetBytes(dataToSend);
stream.Write(send, 0, send.Length);
stream.Flush();
byte[] bytes = new byte[client.ReceiveBufferSize];
int count = stream.Read(bytes, 0, (int)client.ReceiveBufferSize);
String data = Encoding.ASCII.GetString(bytes);
char[] charsToTrim = {‘\0’};//清除後方空白
data = data.TrimEnd(charsToTrim);
Console.WriteLine(data);
String[] StrDataArray = data.Split(Environment.NewLine.ToCharArray());
responseLogin response = JsonConvert.DeserializeObject<responseLogin>(StrDataArray[(StrDataArray.Length-1)]);
Console.WriteLine(response.result);
Console.WriteLine(response.error);
Console.WriteLine(response.datagram);
stream.Close();
client.Close();
}
catch (Exception ex)
{
Console.WriteLine(“request ‘” + “192.168.1.123” + “‘ – ” + ex.Message.ToString());
}
/*
//–http post login
//post元件初始
var httpWebRequest = (HttpWebRequest)WebRequest.Create(“http://192.168.1.123:24410”);
httpWebRequest.ProtocolVersion = HttpVersion.Version10;//http1.0
httpWebRequest.ContentType = “application/json;charset=UTF-8”;
httpWebRequest.Method = “POST”;
//傳送資料
httpWebRequest.ContentLength = output.Length;
StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream());
streamWriter.Write(output);
streamWriter.Flush();
streamWriter.Close();
//接收資料
try
{
WebResponse response = httpWebRequest.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
}
catch (WebException e)
{
Console.WriteLine(“This program is expected to throw WebException on successful run.” +
“\n\nException Message :” + e.Message);
if (e.Status == WebExceptionStatus.ProtocolError)
{
Console.WriteLine(“Status Code : {0}”, ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine(“Status Description : {0}”, ((HttpWebResponse)e.Response).StatusDescription);
}
}
*/
//–
Pause();
}
}
}