Show toolbar

2014年3月26日 星期三

C# POST using WebRequest

標題:C#使用WebRequest POST後取得回傳資料
C# (Program.cs):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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後回傳字串資料的作法。

沒有留言:

張貼留言