C# (Program.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net; //WebRequest WebResponse
using System.IO; //Stream
public class Global
{
public static string server = "http://127.0.0.1:1337";
}
namespace WebPostRequest
{
class Program
{
static string login(string email, string password)
{
//宣告送出資料
string param = "email=" + email + "&password=" + password;
byte[] byteArray = Encoding.UTF8.GetBytes(param);
//Request資料
WebRequest request = WebRequest.Create(Global.server + "/login");
request.Credentials = CredentialCache.DefaultCredentials;
((HttpWebRequest)request).UserAgent = ".NET Framework Example Client";
request.Method = "POST";
request.ContentLength = byteArray.Length;
request.ContentType = "application/x-www-form-urlencoded";
//處理資料流
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
//Response資料
WebResponse response = request.GetResponse();
string rawJsonString = new StreamReader(response.GetResponseStream()).ReadToEnd();
response.Close();
return rawJsonString;
}
static void Main(string[] args)
{
Console.WriteLine( login("test@gmail.com", "abcd1234") );
Console.WriteLine("\r\nPress enter key to continue....");
Console.Read();
}
}
}
說明:
簡單使用WebRequest POST送出email、password後回傳字串資料的作法。
沒有留言:
張貼留言