1.WebClient
public JsonResultEntity HttpTest1(string str, int Num)
{
JsonResultEntity entity = new JsonResultEntity();
try
{
string URL = "API 호출주소";
WebClient webClient = new WebClient();
System.Collections.Specialized.NameValueCollection formData = new System.Collections.Specialized.NameValueCollection();
formData["파라미터"] = str;
formData["파라미터"] = Num;
byte[] responseBytes = webClient.UploadValues(URL, "POST", formData);
string result = Encoding.UTF8.GetString(responseBytes);
//결과값음 Json형식으로 변환
entity = JsonConvert.DeserializeObject<JsonResultEntity>(result);
}
catch (Exception e)
{
//통신 실패시 처리로직
}
return entity;
}
2.HttpWebRequest : x-www-form-urlencoded 방식
public JObject HttpTest2(string str , int Num)
{
string strUri = "API 호출주소"
StringBuilder dataParams = new StringBuilder();
dataParams.Append("str=" + str);
dataParams.Append("&int=" + Num);
// 요청 String -> 요청 Byte 변환
byte[] byteDataParams = UTF8Encoding.UTF8.GetBytes(dataParams.ToString());
try
{
/////////////////////////////////////////////////////////////////////////////////////
/* POST */
// HttpWebRequest 객체 생성, 설정
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUri);
request.Method = "POST"; // 기본값 "GET"
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteDataParams.Length;
// 요청 Byte -> 요청 Stream 변환
Stream stDataParams = request.GetRequestStream();
stDataParams.Write(byteDataParams, 0, byteDataParams.Length);
stDataParams.Close();
// 요청, 응답 받기
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// 응답 Stream 읽기
Stream stReadData = response.GetResponseStream();
StreamReader srReadData = new StreamReader(stReadData, Encoding.UTF8, true);
// 응답 Stream -> 응답 String 변환
string strResult = srReadData.ReadToEnd();
result = JObject.Parse(strResult);
}
catch (Exception e)
{
throw e;
}
return result;
}
3.HttpWebRequest : raw 방식
public APIEntity HttpTest3(string str)
{
//메서드 작성
string content = "{\"method\" : \"메소드명\", \"str \" : [\"" + value + "\"]}";
//Encoding
Encoding encoding = Encoding.UTF8;
byte[] data = encoding.GetBytes(content);
//요청객체 & 요청옵션
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(rpc_url);
request.Method = "POST";
request.PreAuthenticate = true;
request.Headers.Add("Authorization", "인증값");
request.Accept = "text/plain";
//스트림 생성
Stream postStream = request.GetRequestStream();
postStream.Write(data, 0, data.Length);
postStream.Close();
//응답
HttpWebResponse httpresponse = (HttpWebResponse)request.GetResponse();
//응답내용
Stream resultStream = httpresponse.GetResponseStream();
StreamReader reader = new StreamReader(resultStream, Encoding.Default);
//응답내용 읽어 변수에 담기
APIEntity result = JsonConvert.DeserializeObject<APIEntity>(reader.ReadToEnd());
return entity;
}
PInvoke SendKey (0) | 2024.08.07 |
---|---|
OpenCV4 바코드 리딩 (0) | 2024.06.20 |
C# 배포시 난독화를 해야 할까? - ConfuserEx 사용법 (0) | 2021.01.06 |
c# Task 7가지 사용법 (0) | 2021.01.04 |
특정 소수점 자리 이하 올림, 버림, 반올림 (0) | 2019.11.20 |