C# 에서 GET 혹은 POST 방식으로 http 리퀘스트를 보내는 예제.
Get 및 Post 로 원하는 전송 방식에 따라 httpWebRequest.Method 수정하여 사용
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
public static string GetHttpPOST(string[,] reqstring, string url, string encode, ref int errcode)
{
string retValue = string.Empty;
if (url.IndexOf("https://") >= 0)
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
}
try
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "POST";
Stream requestStream = null;
byte[] sendData = null;
if (reqstring != null)
{
string postMsg = String.Empty;
for (int i = 0; i < reqstring.GetLength(0); i++)
{
postMsg += reqstring[i, 0] + "=" + System.Web.HttpUtility.UrlEncode(reqstring[i, 1], Encoding.GetEncoding(encode)) + "&";
}
postMsg = postMsg.Substring(0, postMsg.Length - 1);
if (String.IsNullOrEmpty(encode) || encode == "UTF-8")
{
sendData = UTF8Encoding.UTF8.GetBytes(postMsg);
httpWebRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
}
else if (encode == "EUC-KR")
{
sendData = Encoding.GetEncoding("EUC-KR").GetBytes(postMsg);
httpWebRequest.ContentType = "application/x-www-form-urlencoded; charset=EUC-KR";
}
else
{
sendData = Encoding.GetEncoding("ks_c_5601-1987").GetBytes(postMsg);
httpWebRequest.ContentType = "application/x-www-form-urlencoded; charset=ks_c_5601-1987";
}
httpWebRequest.ContentLength = sendData.Length;
requestStream = httpWebRequest.GetRequestStream();
requestStream.Write(sendData, 0, sendData.Length);
}
else
{
httpWebRequest.ContentLength = 0;
requestStream = httpWebRequest.GetRequestStream();
}
requestStream.Flush();
requestStream.Close();
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding(encode));
retValue = streamReader.ReadToEnd();
streamReader.Close();
httpWebResponse.Close();
}
catch (WebException ex)
{
if (ex.Response is HttpWebResponse)
{
errcode = (int)((HttpWebResponse)ex.Response).StatusCode;
retValue = ex.Message;
}
else
{
retValue = ex.Message;
errcode = -1;
}
}
return retValue;
}
|
cs |
활용 예제
설정된 변수 값은 예제여서 임의로 작성
1
2
3
4
5
6
7
8
9
|
public void HttpPost{
string url = "www.naver.com"; // 통신할 URL
string[,] msg = new String[1, 2] { { "param", "보내는 파라메터" } }; // 전송할 Parameter
string encodeStr = "EUC-KR"; // 인코딩 방식
int errorcode = 0; // 에러 전달받을 값
string returnVal = string.
returnVal = GetHttpPOST(msg, url, encodeStr, ref errorcode);
}
|
cs |
'개발 > C#.net' 카테고리의 다른 글
[C#] multipart/form-data 파일 업로드 (1) | 2023.05.13 |
---|