테스트 1차
HttpWebRequest 방식
파일 업로드 부분이 까다로움.. 따로 다 (내용을 붙여 주어야 함)
public static string GetURIRequestImageUpload(string uri, string postParam = null, string cookieValue = null, Encoding encoding = null, string contentType = null, string credentials = null, string headerName = null, string headerValue = null, string method = null, string saveFile = null, System.IO.Stream saveFileSteam = null, int fileLength = 0)
{
if (encoding == null) encoding = Encoding.UTF8;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
if (!string.IsNullOrEmpty(credentials))
{
request.UseDefaultCredentials = true;
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
}
if (!string.IsNullOrEmpty(cookieValue))
{
request.Headers.Add(HttpRequestHeader.Cookie, cookieValue);
}
if (!string.IsNullOrEmpty(headerName) && !string.IsNullOrEmpty(headerValue))
{
request.Headers.Add(headerName, headerValue);
}
if (!string.IsNullOrEmpty(method))
{
request.Method = method;
}
else
{
request.Method = "POST";
}
request.ContentType = contentType;
//stream.Seek(0, SeekOrigin.Begin);
//byte[] buffer = new byte[stream.Length];
//int count = 0;
//while (count < stream.Length)
//{
// buffer[count++] = Convert.ToByte(stream.ReadByte());
//}
//request.ContentLength = buffer.Length;
//using (Stream sendStream = request.GetRequestStream())
//{
// sendStream.Write(buffer, 0, buffer.Length);
// sendStream.Close();
//}
//string result = "";
//using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
//{
// Stream dataStream = response.GetResponseStream();
// StreamReader reader = new StreamReader(dataStream, encoding);
// result = reader.ReadToEnd();
// reader.Close();
// dataStream.Close();
// response.Close();
//}
if (!string.IsNullOrEmpty(postParam))
{
if (!string.IsNullOrEmpty(contentType))
request.ContentType = contentType;
else
request.ContentType = @"application/x-www-form-urlencoded";
//
string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
string fileFormName = "file";
string contenttype = "application/octet-stream";
// Build up the post message header
StringBuilder sb = new StringBuilder();
sb.Append("--");
sb.Append(boundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append(fileFormName);
sb.Append("\"; filename=\"");
sb.Append(saveFile);
sb.Append("\";");
sb.Append(postParam);
sb.Append("\r\n");
sb.Append("Content-Type: ");
sb.Append(contenttype);
sb.Append("\r\n");
sb.Append("\r\n");
string postHeader = sb.ToString();
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);
// Build the trailing boundary string as a byte array
// ensuring the boundary appears on a line by itself
byte[] boundaryBytes =
Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
long length = postHeaderBytes.Length + fileLength + boundaryBytes.Length;
request.ContentLength = length;
Stream requestStream = request.GetRequestStream();
// Write out our post header
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
// Write out the file contents
byte[] buffer = new Byte[checked((uint)Math.Min(4096,
(int)fileLength))];
int bytesRead = 0;
while ((bytesRead = saveFileSteam.Read(buffer, 0, buffer.Length)) != 0)
requestStream.Write(buffer, 0, bytesRead);
// Write out the trailing boundary
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
requestStream.Close();
requestStream = null;
//byte[] buffer = encoding.GetBytes(postParam);
//request.ContentLength = buffer.Length;
//Stream sendStream = request.GetRequestStream();
//sendStream.Write(buffer, 0, buffer.Length);
//sendStream.Close();
}
string result = "";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream, encoding);
result = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
return result;
}
테스트 2차
HttpClient 방식
파일업로드시 form-data.
앞뒤 content.Add 로 기본 내용(앞,뒤에 자동으로 붙는 부분)이 들어간다. 간략해짐.
public static string GetURIRequestImageUpload2(string uri, string postParam = null, int serviceId=0, string registrationNo=null, long memberSN = 0, string headerName = null, string headerValue = null, string method = null, string saveFile = null, System.IO.Stream saveFileSteam = null, int fileLength = 0)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add(headerName, headerValue);
//client.DefaultRequestHeaders.Add("Content-Type", "application/json");
//using (var content = new MultipartFormDataContent())
//{
// //Content-Disposition: form-data; name="json"
// //var stringContent = new StringContent("");
// //stringContent.Headers.Add("Content-Disposition", "form-data; name=\""+ postParam + "\"");
// content.Add(new StringContent(serviceId.ToString()), "serviceId");
// content.Add(new StringContent(registrationNo), "registrationNo");
// content.Add(new StringContent(memberSN.ToString()), "memberSN");
// var streamContent = new StreamContent(saveFileSteam);
// //streamContent.Headers.Add("Content-Type", "application/octet-stream");
// streamContent.Headers.Add("Content-Type", "application/octet-stream");
// streamContent.Headers.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"c:\\" + saveFile + "\"");
// content.Add(streamContent, "file", "c:\\"+saveFile);
// var message = client.PutAsync(uri, content);
// var input = message.Result.Content.ReadAsStringAsync();
// Console.WriteLine(input.Result);
// Console.Read();
// return input.Result.ToString();
//}
using (var content = new MultipartFormDataContent())
{
content.Add(new StringContent(serviceId.ToString()), "serviceId");
content.Add(new StringContent(registrationNo), "registrationNo");
content.Add(new StringContent(memberSN.ToString()), "memberSN");
var streamContent = new StreamContent(saveFileSteam);
streamContent.Headers.Add("Content-Type", "image/jpeg");
content.Add(streamContent, "file", "/C:/"+saveFile);
var message = client.PutAsync(uri, content);
var input = message.Result.Content.ReadAsStringAsync();
return input.Result.ToString();
}
}
}
```
2차 간략하게 처리 됨.
파일 업로드 관련 참조
https://stackoverrun.com/ko/q/3524546
http://blog.naver.com/PostView.nhn?blogId=eastee&logNo=20117770155&redirect=Dlog&widgetTypeCall=true
https://stackoverflow.com/questions/1131425/send-a-file-via-http-post-with-c-sharp
https://stackoverflow.com/questions/15195586/httppost-and-webapi
https://www.it-swarm.dev/ko/c%23/httpclient%EC%97%90-%EB%8C%80%ED%95%9C-contenttype-%ED%97%A4%EB%8D%94%EB%A5%BC-%EC%84%A4%EC%A0%95-%ED%95%98%EC%8B%9C%EA%B2%A0%EC%8A%B5%EB%8B%88%EA%B9%8C/1066841790/
https://stackoverflow.com/questions/48164503/httpclient-multipart-form-data-post-image-and-json-same-time
https://www.it-swarm.dev/ko/c%23/c-httpclient-45-%EB%A9%80%ED%8B%B0-%ED%8C%8C%ED%8A%B8-%EC%96%91%EC%8B%9D-%EB%8D%B0%EC%9D%B4%ED%84%B0-%EC%97%85%EB%A1%9C%EB%93%9C/1073693525/
'프로그램&코딩 > Coding' 카테고리의 다른 글
모바일 페이지에서 폰트 사이즈 조절 text-size-adjust (0) | 2022.10.07 |
---|---|
SQL(MSSQL) like 검색 array parameter 처리 (0) | 2021.10.26 |
MSSQL 테이블을 배열로 반환하기 (0) | 2019.06.24 |
정규식(Regex) 변환(replace) 및 이메일, 핸드폰번호, 전화번호 등 체크하기 (0) | 2019.02.13 |
C# 에서 영문, 숫자를 # 변환(치환)하기 ( # 으로 변경하기 ) (0) | 2018.11.23 |
OnSelectedIndexChanged 인 경우에도 응답이 없을 경우.. (0) | 2017.09.13 |