C# HttpClientUtil 도구 클래스 양식 요청 첨부 파일 업로드 다운로드
, !
Post 、Delete、Get( )、Put 。
, , 、 。
public class HttpClientUtil
{
///
/// post
///
///
/// post
///
public static string PostResponse(string url, string postData)
{
if (url.StartsWith("https"))
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
HttpContent httpContent = new StringContent(postData);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
return result;
}
return null;
}
///
/// post
///
///
/// url
/// post
///
public static string PostResponse(string url, T postData) where T : class,new()
{
string result = "0";
var format = new IsoDateTimeConverter();
format.DateTimeFormat = "yyyyMMddHHmmssSSS";
var dataJson = JsonConvert.SerializeObject(postData, Newtonsoft.Json.Formatting.Indented, format);
var content = new StringContent(dataJson, Encoding.UTF8, "application/json");
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = httpClient.PostAsync(url, content).Result;
if (response.IsSuccessStatusCode)
{
//Task t = response.Content.ReadAsStringAsync();
//string s = t.Result;
//T ss = JsonConvert.DeserializeObject(s);
result = "1";
}
return result;
}
///
/// post
///
///
/// url
/// post
///
public static string PostResponseKey(string url, T postData) where T : class,new()
{
string ret = "0";
var format = new IsoDateTimeConverter();
format.DateTimeFormat = "yyyyMMddHHmmssSSS";
var dataJson = JsonConvert.SerializeObject(postData, Newtonsoft.Json.Formatting.Indented, format);
var content = new StringContent(dataJson, Encoding.UTF8, "application/json");
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = httpClient.PostAsync(url, content).Result;
if (response.IsSuccessStatusCode)
{
Task t = response.Content.ReadAsStringAsync();
ret = t.Result;
}
return ret;
}
///
/// post
///
///
/// url
/// post
///
public static T PostResponse(string url, string postData) where T : class,new()
{
//if (postData != null)
//{
// if (url.StartsWith("https"))
// System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
// HttpClient httpClient = new HttpClient();
// var format = new IsoDateTimeConverter();
// format.DateTimeFormat = "yyyyMMddHHmmssSSS";
// var dataJson = JsonConvert.SerializeObject(postData, Newtonsoft.Json.Formatting.Indented, format);
// var content = new StringContent(dataJson, Encoding.UTF8, "application/json");
// HttpResponseMessage response = httpClient.PutAsync(url, content).Result;
// if (response.IsSuccessStatusCode)
// {
// result = "1";
// }
//}
if (url.StartsWith("https"))
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
HttpContent httpContent = new StringContent(postData);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpClient httpClient = new HttpClient();
T result = default(T);
HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
if (response.IsSuccessStatusCode)
{
Task t = response.Content.ReadAsStringAsync();
string s = t.Result;
result = JsonConvert.DeserializeObject(s);
}
return result;
}
///
/// V3 Xml ,
///
///
///
///
///
public static T PostXmlResponse(string url, string xmlString) where T : class,new()
{
if (url.StartsWith("https"))
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
HttpContent httpContent = new StringContent(xmlString);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpClient httpClient = new HttpClient();
T result = default(T);
HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
if (response.IsSuccessStatusCode)
{
Task t = response.Content.ReadAsStringAsync();
string s = t.Result;
result = XmlDeserialize(s);
}
return result;
}
///
/// Xml
///
///
///
///
public static T XmlDeserialize(string xmlString) where T : class,new ()
{
try
{
XmlSerializer ser = new XmlSerializer(typeof(T));
using (StringReader reader = new StringReader(xmlString))
{
return (T)ser.Deserialize(reader);
}
}
catch (Exception ex)
{
throw new Exception("XmlDeserialize :xmlString:" + xmlString + " :" + ex.Message);
}
}
///
/// get
///
///
///
public static string GetResponse(string url)
{
if (url.StartsWith("https"))
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = httpClient.GetAsync(url).Result;
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
return result;
}
return null;
}
///
/// get
///
///
///
///
public static T GetResponse(string url) where T : class,new()
{
if (url.StartsWith("https"))
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
HttpClient httpClient = new HttpClient();
httpClient.Timeout = TimeSpan.FromMilliseconds(3000);
httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = httpClient.GetAsync(url).Result;
T result = default(T);
if (response.IsSuccessStatusCode)
{
Task t = response.Content.ReadAsStringAsync();
string s = t.Result;
result = JsonConvert.DeserializeObject(s);
}
return result;
}
///
/// Get List
///
///
///
/// List
public static List GetResponseList(string url) where T : class,new()
{
if (url.StartsWith("https"))
{
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
}
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = httpClient.GetAsync(url).Result;
List result = default(List);
if (response.IsSuccessStatusCode)
{
Task t = response.Content.ReadAsStringAsync();
string s = t.Result;
if (s != null && !s.StartsWith("["))
{
s = "[" +s +"]";
}
result = JsonConvert.DeserializeObject>(s);
}
return result;
}
///
/// Delete
///
///
/// post
///
public static string DeleteResponse(string url)
{
if (url.StartsWith("https"))
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = httpClient.DeleteAsync(url).Result;
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
return "1";
}
return "0";
}
///
/// put List
///
///
/// url
/// put
///
public static string PutListDataResponse(string url, List postData) where T : class,new()
{
string result = "0";
if (postData != null && postData.Count > 0)
{
if (url.StartsWith("https"))
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
HttpClient httpClient = new HttpClient();
var format = new IsoDateTimeConverter();
format.DateTimeFormat = "yyyyMMddHHmmssSSS";
var dataJson = JsonConvert.SerializeObject(postData[0], Newtonsoft.Json.Formatting.Indented, format);
var content = new StringContent(dataJson, Encoding.UTF8, "application/json");
HttpResponseMessage response = httpClient.PutAsync(url, content).Result;
if (response.IsSuccessStatusCode)
{
result = "1";
}
}
else
{
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = httpClient.PutAsync(url, null).Result;
if (response.IsSuccessStatusCode)
{
result = "1";
}
}
return result;
}
///
/// put ( )
///
///
/// url
/// put
///
public static string PutDataResponse(string url, T postData) where T : class,new()
{
string result = "0";
if (postData != null )
{
if (url.StartsWith("https"))
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
HttpClient httpClient = new HttpClient();
var format = new IsoDateTimeConverter();
format.DateTimeFormat = "yyyyMMddHHmmssSSS";
var dataJson = JsonConvert.SerializeObject(postData, Newtonsoft.Json.Formatting.Indented, format);
var content = new StringContent(dataJson, Encoding.UTF8, "application/json");
HttpResponseMessage response = httpClient.PutAsync(url, content).Result;
if (response.IsSuccessStatusCode)
{
result = "1";
}
}
else
{
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = httpClient.PutAsync(url, null).Result;
if (response.IsSuccessStatusCode)
{
result = "1";
}
}
return result;
}
}
양식 제출, 첨부 파일(사진 밤 들기) 업로드, 다운로드 코드:
첫 번째 단계: 실체 클래스를 가져오고 반사를 통해 키 값이 맞습니다.
People people = new People();
people 할당...
class GetEntityKeyValue
{
public static Dictionary getProperties(T t) where T : class // , T Class 。
{
Dictionary dic = new Dictionary();
Type type = t.GetType();// Type
// Type.GetProperties PropertyInfo[], foreach
foreach (PropertyInfo pi in type.GetProperties())
{
object value1 = pi.GetValue(t, null);// pi.GetValue
string name = pi.Name;// ,
//
dic.Add(name,value1);
}
return dic;
}
}
Dictionarydic= GetEntityKeyValue.getProperties(people );
2단계: 첨부 파일 업로드 및 양식 데이터 제출
HttpClient httpClient = new HttpClient();
string url = "******************";
string filename = "******";//
using (var form = new MultipartFormDataContent())
{ string fileName = Path.GetFileNameWithoutExtension(imagePath);
var imageContent = new ByteArrayContent(ImageHelper.ImageToBytes(finishImg)); imageContent.Headers.Add("Content-Type", "multipart/form-data"); imageContent.Headers.Add("Content-Disposition", "form-data; name=\"sketch\"; filename=\"" + fileName + "\""); form.Add(imageContent, "sketch", fileName); foreach (var keyValuePair indic) { if (keyValuePair.Value != null) { form.Add(new StringContent(keyValuePair.Value.ToString()), String.Format("\"{0}\"", keyValuePair.Key)); } } var response = httpClient.PostAsync(url, form).Result; if (response.StatusCode == System.Net.HttpStatusCode.OK) { // 200 } else { // } }
3단계: 이미지 다운로드
HttpClient httpClient = new HttpClient();
HttpResponseMessage responseImg = httpClient.GetAsync(new Uri(url)).Result;
Stream streamIMg = responseImg.Content.ReadAsStreamAsync().Result;
byte[] bytes = new byte[streamIMg.Length];
streamIMg.Read(bytes, 0, bytes.Length);
//
streamIMg.Seek(0, SeekOrigin.Begin);
//
// ImageHelper ,bytes Image
// finishImg = ImageHelper.BytesToImage(bytes);
StackOverFlow 。 , !
, , !
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
WebView2를 Visual Studio 2017 Express에서 사용할 수 있을 때까지Evergreen .Net Framework SDK 4.8 VisualStudio2017에서 NuGet을 사용하기 때문에 패키지 관리 방법을 packages.config 대신 PackageReference를 사용해야...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.