public HttpHeader(HttpStatusCode s, HttpContentType cType, long cLen) { StatusCode = s; ContentType = HttpContentTypeStrings[(int)cType]; ContentLength = cLen; isBinary = ContentTypeIsBinary(cType); }
private void AddBody(HttpWebRequest httpRequest, HttpContentType contentType, Payload payload) { using (var body = contentType.Format(payload)) { httpRequest.ContentLength = body.ContentLength; httpRequest.ContentType = body.ContentType; using (var outStream = httpRequest.GetRequestStream()) { Copy(body.Open(), outStream); } } }
public override Response Post(Uri uri, HttpContentType contentType, Payload payload) { var unauthorized = new Request(RequestLine.Post(uri), payload) { ContentType = contentType.ContentType }; var authorized = AuthorizeAndConvert(unauthorized); AddBody(authorized, contentType, payload); return TryExecute(authorized); }
public static IHttpContent BuildHttpContent(HttpContentType type, object data) { switch(type) { case HttpContentType.Json: return new HttpJsonContent(data); case HttpContentType.Xml: return null;//TODO: add xml serializer case HttpContentType.Text: return new HttpStringContent(data.ToString()); default: return null; } }
/// <summary> /// 执行Post请求 /// 可接受IDictionary<string,object>,IEnumerable<keyvaluePair<string,object>>, /// IEnumerable<object>,string(a=a1&b=b1),object等类型参数 /// </summary> /// <param name="url">请求url</param> /// <param name="requestParams">请求参数</param> /// <param name="contentType">请求内容类型</param> /// <returns></returns> public string Post(string url, object requestParams = null, HttpContentType contentType = HttpContentType.Json) { string result = ""; try { using (HttpWebResponse response = CreatePostHttpResponse(url, requestParams, contentType)) { result = ReadResponse(response); response.Close(); } } catch (System.Exception ex) { throw new System.Exception(ex.Message); } return(result); }
public static IParamGenerator GetParamGenerator(HttpContentType type) { var typeStr = type.ToString(); if (typeStr == HttpContentType.TextXml.ToString() || typeStr == HttpContentType.ApplicationXml.ToString()) { return(new XMLGenerator()); } else if (typeStr == HttpContentType.Json.ToString()) { return(new JsonGenerator()); } else { return(new FormGenerator()); } }
private static HttpContentType DetectContentType(HttpContent content) { HttpContentType contentType = HttpContentType.Null; if (content != null) { if (HttpUtilities.IsHttpContentBinary(content)) { contentType = HttpContentType.Binary; } else { contentType = HttpContentType.Ascii; } } return(contentType); }
private static void WriteResponseFile(string pathFileName, HttpContentType mimeType, IOutputStream outputStream, bool readFromLocalFolder) { Task <StorageFile> fileTask = null; if (readFromLocalFolder) { fileTask = ApplicationData.Current.LocalFolder.GetFileAsync(pathFileName).AsTask(); } else { fileTask = Package.Current.InstalledLocation.GetFileAsync(@"Web" + pathFileName).AsTask(); } fileTask.Wait(); byte[] file = null; switch (mimeType) { case HttpContentType.Html: case HttpContentType.Text: case HttpContentType.Json: case HttpContentType.JavaScript: case HttpContentType.Css: var fileStringTask = FileIO.ReadTextAsync(fileTask.Result).AsTask(); fileStringTask.Wait(); var textBytes = Encoding.UTF8.GetBytes(fileStringTask.Result); file = textBytes; break; case HttpContentType.Jpeg: case HttpContentType.Png: var fileImageTask = FileIO.ReadBufferAsync(fileTask.Result).AsTask(); fileImageTask.Wait(); var fileImage = fileImageTask.Result; file = new byte[fileImage.Length]; fileImage.CopyTo(file); break; } WriteResponse(mimeType, file, HttpStatusCode.HttpCode200, outputStream); }
/// <summary> /// 执行Post请求 /// 可接受IDictionary<string,object>,IEnumerable<keyvaluePair<string,object>>, /// IEnumerable<object>,string(a=a1&b=b1),object等类型参数 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="url">请求url</param> /// <param name="requestParams">请求参数</param> /// <param name="contentType">请求内容类型</param> /// <returns></returns> public AfterDto <T> PostAsync <T>(string url, object requestParams = null, HttpContentType contentType = HttpContentType.Json) { AfterDto <T> afterDto = null; Task t = new Task(() => { string resultString = Post(url, requestParams, contentType); if (typeof(T) == typeof(string)) { T result = (T)Convert.ChangeType(resultString, typeof(T)); afterDto.DoAfter(result); } else { afterDto.DoAfter(JsonHelper.DeserializeObject <T>(resultString)); } }); t.Start(); return(afterDto); }
public static string ConvertToString(this HttpContentType httpContentType) { switch (httpContentType) { case HttpContentType.form: return("application/x-www-form-urlencoded"); case HttpContentType.file: return("multipart/form-data"); case HttpContentType.json: return("application/json"); case HttpContentType.xml: return("text/xml"); default: return("application/x-www-form-urlencoded"); } }
public HttpBodyObject(IReadOnlyDictionary <string, string> fields, string content) { if (fields != null) { if (fields.ContainsKey("content-disposition")) { ContentDisposition = new HttpContentDisposition(fields["content-disposition"]); } else { throw new Exception(); } if (fields.ContainsKey("content-type")) { ContentType = new HttpContentType(fields["content-type"]); } } Content = content; }
public HttpWebRequestOption(string uri, HttpWebHeaderContent headContent, Encoding encoding, HttpMethod method = HttpMethod.POST, HttpContentType contentType = HttpContentType.JSON) { this.Uri = uri; this.HttpMethod = method; this.HeadContent = headContent; this.ContentType = contentType; if (encoding == null) { this.Encoding = DEFAULT_ENCODING; } else { this.Encoding = encoding; } }
private static async Task <T> HttpPost <T>(string url, string body, HttpContentType httpContentType) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.Proxy = null; request.Accept = "text/html, application/xhtml+xml, */*"; switch (httpContentType) { case HttpContentType.Form: request.ContentType = "multipart/form-data,"; break; case HttpContentType.xForm: request.ContentType = "application/x-www-form-urlencoded"; break; case HttpContentType.Xml: request.ContentType = "text/xml"; break; default: request.ContentType = "application/json"; break; } byte[] buffer = Encoding.UTF8.GetBytes(body); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); var responseContent = string.Empty; HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { responseContent = reader.ReadToEnd(); } return(JsonConvert.DeserializeObject <T>(responseContent)); }
private static HttpContent GetHttpContent( HttpContentType contentType, IDictionary <string, string> args, IDictionary <string, string> argsHeader, bool json) { HttpContent content; if (args != null) { if (json) { var jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(args); content = new StringContent(jsonStr); content.Headers.ContentType = new MediaTypeHeaderValue(contentType.GetContentType()); } else { content = new StringContent(string.Join("&", args.Select(k => $"{k.Key}={k.Value}"))); content.Headers.ContentType = new MediaTypeHeaderValue(contentType.GetContentType()); } } else { content = new StringContent(""); content.Headers.ContentType = new MediaTypeHeaderValue(HttpContentType.Form.GetContentType()); } if (argsHeader != null) { foreach (var item in argsHeader) { content.Headers.Add(item.Key, item.Value); } } return(content); }
/// <summary> /// http post /// </summary> /// <param name="url">request url</param> /// <param name="data">rqeuest data</param> /// <param name="contentType">http contenttype enum</param> /// <returns>http response</returns> public static string Post(string url, string data, HttpContentType contentType) { if (!url.StartsWith("http")) { url = $"http://{url}"; } var request = WebRequest.Create(url); request.ContentType = contentType.ConvertToString(); request.Method = "POST"; WriteRequestData(request, data); var response = (HttpWebResponse)request.GetResponse(); /*var html = ""; * Encoding enc = Encoding.GetEncoding("UTF-8"); * using (StreamReader sr = new StreamReader(response.GetResponseStream(), enc)) * { * html = sr.ReadToEnd(); * } * return Encoding.UTF8.GetBytes(html);*/ var size = 8192; var buffer = new byte[size]; var stream = response.GetResponseStream(); var readed = 0; var ms = new MemoryStream(); while ((readed = stream.Read(buffer, 0, size)) > 0) { ms.Write(buffer, 0, readed); } stream.Close(); var byts = ms.ToArray(); ms.Close(); return(Encoding.UTF8.GetString(byts)); }
public abstract Response Post(Uri uri, HttpContentType contentType, Payload payload);
/// <summary> /// 设置内容类型 /// </summary> /// <param name="contentType">内容类型</param> public TRequest ContentType(HttpContentType contentType) => ContentType(contentType.Description());
/// <summary> /// 执行Post请求 /// 可接受IDictionary<string,object>,IEnumerable<keyvaluePair<string,object>>, /// IEnumerable<object>,string(a=a1&b=b1),object等类型参数 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="url">请求的url</param> /// <param name="requestParams">请求参数</param> /// <param name="contentType">请求内容类型</param> /// <returns></returns> public T Post <T>(string url, object requestParams = null, HttpContentType contentType = HttpContentType.Json) { string resultString = Post(url, requestParams, contentType); return(JsonHelper.DeserializeObject <T>(resultString)); }
/// <summary> /// Post请求[异步] /// </summary> /// <param name="host">域名</param> /// <param name="apiName">接口名称(接口地址)</param> /// <param name="dicParameters">接口参数</param> /// <param name="headers">请求头</param> /// <param name="timeout">请求响应超时时间,单位/s(默认100秒)</param> /// <param name="contentType">请求类型</param> /// <param name="isMultilevelNestingJson">是否为多层嵌套json</param> /// <returns></returns> public async Task <string> HttpPostAsync(string host, string apiName, IDictionary <string, string> dicParameters, Dictionary <string, string> headers = null, int timeout = 100, HttpContentType contentType = HttpContentType.Json, bool isMultilevelNestingJson = false) { var client = clientFactory.CreateClient("base"); { #region Http基础设置 //设置接口超时时间 if (timeout > 0) { client.Timeout = new TimeSpan(0, 0, timeout); } HttpContent content = new FormUrlEncodedContent(dicParameters); var _contentType = (contentType == HttpContentType.Json ? "application/json" : "application/x-www-form-urlencoded"); if (contentType == HttpContentType.Json) { if (isMultilevelNestingJson) { content = new StringContent(dicParameters["json"]); } else { content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(dicParameters)); } } content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(_contentType); //设置HTTP请求头 if (headers != null) { foreach (KeyValuePair <string, string> header in headers) { content.Headers.Add(header.Key, header.Value); } } #endregion #region 新增请求日志 var log_request_param = new AddRequestLogParam(); log_request_param.APIName = apiName.ToString().ToLower(); log_request_param.ClientHost = SysUtil.Ip; log_request_param.RequestTime = DateTime.Now; log_request_param.ServerHost = host; log_request_param.SystemID = SysUtil.GetSystemId(); log_request_param.TraceID = PoJun.Util.Helpers.Id.GetGuidBy32(); log_request_param.Level = 2; log_request_param.ParentTraceID = SysUtil.GetTraceId(); log_request_param.RequestBody = Newtonsoft.Json.JsonConvert.SerializeObject(dicParameters); if (SysUtil.GetTraceId() != null) { log_request_param.Level = 2; log_request_param.ParentTraceID = SysUtil.GetTraceId(); } else { log_request_param.Level = 1; } var log_request_result = await apiLogService.AddRequestLogAsync(log_request_param); #endregion #region 发起Http请求 var url = $"{host}{apiName}"; //异步发送请求 var events = await client.PostAsync(url, content); //异步获取请求的结果 var strResult = await events.Content.ReadAsStringAsync(); #endregion #region 新增响应日志 var log_response_param = new AddResponseLogParam(); log_response_param.IsError = false; log_response_param.ParentTraceID = log_request_param.TraceID; log_response_param.ResponseBody = strResult; log_response_param.ResponseTime = DateTime.Now; log_response_param.TimeCost = Convert.ToInt32((log_response_param.ResponseTime - log_request_param.RequestTime).TotalMilliseconds); await apiLogService.AddResponseLogAsync(log_response_param); #endregion #region 返回结果 return(strResult); #endregion } }
public static void WriteResponseFile(string pathFileName, HttpContentType mimeType, IOutputStream outputStream) { WriteResponseFile(pathFileName, mimeType, outputStream, false); }
public static void WriteResponseFile(byte[] content, HttpContentType mimeType, IOutputStream outputStream) { WriteResponse(mimeType, content, HttpStatusCode.HttpCode200, outputStream); }
public ContentTypeAttribute(string value) { ContentType = value; }
public static string GetTypeMime(HttpContentType contentType) { return(ContentTypes[contentType]); }
/// <summary> /// 创建Post方式的HTTP请求 /// 可接受IDictionary<string,object>,IEnumerable<keyvaluePair<string,object>>, /// IEnumerable<object>,string(a=a1&b=b1),object等类型参数 /// </summary> /// <param name="url">请求url</param> /// <param name="requestParams">请求参数</param> /// <param name="contentType">请求内容类型</param> /// <returns></returns> public HttpWebResponse CreatePostHttpResponse(string url, object requestParams = null, HttpContentType contentType = HttpContentType.Json) { if (!url.ToLower().StartsWith("http") && !string.IsNullOrEmpty(BaseUrl)) { url = BaseUrl + url; } if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { //如果是发送HTTPS请求 request.ProtocolVersion = HttpVersion.Version10; request.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); } request.Method = "POST"; if (contentType == HttpContentType.Json) { request.Accept = "application/json"; request.ContentType = "application/json;charset=utf-8;"; } else if (contentType == HttpContentType.Form) { request.ContentType = "application/x-www-form-urlencoded"; } request.UserAgent = UserAgent; if (Headers != null && Headers.Count > 0) { foreach (string key in Headers.AllKeys) { request.Headers.Add(key, Headers[key]); } } request.Timeout = Timeout; request.ReadWriteTimeout = Timeout; request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(Cookies); //如果需要Post数据 if (requestParams != null) { string paramStr = null; if (contentType == HttpContentType.Json) { paramStr = JsonHelper.SerializeObject(requestParams); } else { paramStr = GetParameterString(requestParams); } if (!string.IsNullOrEmpty(paramStr)) { byte[] data = DefaultEncoding.GetBytes(paramStr); using (Stream stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } } } return(request.GetResponse() as HttpWebResponse); }
protected Response Post(Uri uri, HttpContentType contentType, Payload payload) { var response = _internet.Post(uri, contentType, payload); EnsureAuthorized(response); return response; }
/// <summary> /// Create <see cref="HttpApiTransport"/> from an existing <see cref="HttpClient"/> instance. /// </summary> /// <param name="client">Existing HTTP client instance.</param> /// <param name="contentType">Content type to use in requests. /// Used to set Content-Type and Accept HTTP headers.</param> public HttpApiTransport(HttpClient client, HttpContentType contentType) { _client = client; _contentType = contentType; }
/// <summary> /// Post请求[同步] /// </summary> /// <typeparam name="T"></typeparam> /// <param name="host">域名</param> /// <param name="apiName">接口名称(接口地址)</param> /// <param name="dicParameters">接口参数</param> /// <param name="httpHandler">httpHandler</param> /// <param name="headers">请求头</param> /// <param name="timeout">请求响应超时时间,单位/s(默认100秒)</param> /// <param name="contentType">请求类型</param> /// <returns></returns> public T HttpPost <T>(string host, string apiName, IDictionary <string, string> dicParameters, DiscoveryHttpClientHandler httpHandler = null, Dictionary <string, string> headers = null, int timeout = 100, HttpContentType contentType = HttpContentType.Json) { using (HttpClient client = ((httpHandler == null) ? new HttpClient() : new HttpClient(httpHandler))) { #region Http基础设置 //设置接口超时时间 if (timeout > 0) { client.Timeout = new TimeSpan(0, 0, timeout); } HttpContent content = new FormUrlEncodedContent(dicParameters); var _contentType = (contentType == HttpContentType.Json ? "application/json" : "application/x-www-form-urlencoded"); if (contentType == HttpContentType.Json) { content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(dicParameters)); } content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(_contentType); //设置HTTP请求头 if (headers != null) { foreach (KeyValuePair <string, string> header in headers) { content.Headers.Add(header.Key, header.Value); } } #endregion #region 新增请求日志 var log_request_param = new AddRequestLogParam(); log_request_param.APIName = apiName; log_request_param.ClientHost = PoJun.Util.Helpers.Web.Host; log_request_param.RequestTime = DateTime.Now; log_request_param.ServerHost = host; log_request_param.SystemID = SysUtil.GetSystemId(); log_request_param.TraceID = PoJun.Util.Helpers.Id.GetGuidBy32(); log_request_param.RequestBody = Newtonsoft.Json.JsonConvert.SerializeObject(dicParameters); if (SysUtil.GetTraceId() != null) { log_request_param.Level = 2; log_request_param.ParentTraceID = SysUtil.GetTraceId(); } else { log_request_param.Level = 1; } var log_request_result = apiLogService.AddRequestLogAsync(log_request_param).Result; #endregion #region 发起Http请求 var url = $"{host}{apiName}"; //异步发送请求 var events = client.PostAsync(url, content).Result; //异步获取请求的结果 var strResult = events.Content.ReadAsStringAsync().Result; #endregion #region 新增响应日志 var log_response_param = new AddResponseLogParam(); log_response_param.IsError = false; log_response_param.ParentTraceID = log_request_param.TraceID; log_response_param.ResponseBody = strResult; log_response_param.ResponseTime = DateTime.Now; log_response_param.TimeCost = Convert.ToInt32((log_response_param.ResponseTime - log_request_param.RequestTime).TotalMilliseconds); apiLogService.AddResponseLogAsync(log_response_param).Wait(); #endregion #region 返回结果 return(Newtonsoft.Json.JsonConvert.DeserializeObject <T>(strResult)); #endregion } }
public ContentTypeAttribute(HttpContentTypes value) { ContentType = value; }
protected Response Post(Uri uri, HttpContentType contentType, Payload payload) { return Internet.Post(uri, contentType, payload); }
/// <summary> /// 设置内容类型 /// </summary> /// <param name="contentType">内容类型</param> public TRequest ContentType(HttpContentType contentType) { return(ContentType(EnumTool.GetDescription <HttpContentType>(contentType))); }
public static void WriteResponseFileFromLocalFolder(string pathFileName, HttpContentType mimeType, IOutputStream outputStream) { WriteResponseFile(pathFileName, mimeType, outputStream, true); }
public ServiceOption() { this.DefaultContentType = HttpContentType.ApplicationJson; }
/// <summary> /// 发生post请求 /// </summary> /// <param name="Url"></param> /// <param name="postDataStr"></param> /// <returns></returns> public static async Task <string> DoHttpPostAsync(string Url, string postDataStr, HttpContentType contentType = HttpContentType.JSON, int timeOut = 300000) { HttpResquestEntity requestEntity = new HttpResquestEntity() { Url = Url, SendData = postDataStr, Timeout = timeOut, ContentType = contentType }; HttpWebRequest request = CreateRequest(requestEntity); //using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) using (var response = await request.GetResponseAsync()) { Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return(retString); } }
public XPRequestParam SetObjectBody(object obj, HttpContentType contentType) { return SetBody(HttpContentFactory.BuildHttpContent(contentType, obj)); }
/// <summary> /// 设置内容类型 /// </summary> /// <param name="contentType">内容类型</param> public TRequest ContentType(HttpContentType contentType) { return(ContentType(contentType.Description())); }
/// <summary> /// 设置内容类型 /// </summary> /// <param name="contentType">内容类型</param> public TRequest ContentType(HttpContentType contentType) { return(ContentType(EnumUtil.GetEnumDescription(contentType))); }
/// <summary> /// 直接序列化结果 /// </summary> /// <param name="actionName"></param> /// <param name="type"></param> public TResult HttpPost <TResult>(string actionName, IDictionary <string, object> headers = null, object body = null, HttpContentType type = HttpContentType.ApplicationJson, params Tuple <string, object>[] parames) { TResult result = default(TResult); HttpClient client = new HttpClient(); client.BaseAddress = new Uri(this.Option.BaseAddress); if (headers == null) { headers = new Dictionary <string, object>(); } if (!headers.ContainsKey("Content-Type")) { switch (type) { case HttpContentType.Unknown: break; case HttpContentType.ApplicationJson: headers.Add("Content-Type", "application/json"); break; case HttpContentType.FormUrlEncoded: headers.Add("Content-Type", "application/x-www-form-urlencoded"); break; default: break; } } string relativeUrl = BuildRelativeUrl(actionName, parames); HttpContent content = BuildContent(headers, body); HttpResponseMessage msg = client.PostAsync(relativeUrl, content).Result; if (msg.StatusCode == System.Net.HttpStatusCode.OK) { string str = msg.Content.ReadAsStringAsync().Result; result = JsonConvert.DeserializeObject <TResult>(str); if (result == null) { this.logger.LogError("convert error: " + str); } } else { if (msg.StatusCode == System.Net.HttpStatusCode.BadRequest && logger != null) { this.logger.LogInformation(actionName); if (body != null) { this.logger.LogInformation(JsonConvert.SerializeObject(body)); } string _log = msg.Content.ReadAsStringAsync().Result; this.logger.LogError(_log); } throw new HttpRequestException(string.Format("status = {0}:{1}", (int)msg.StatusCode, msg.StatusCode)); } return(result); }
public HttpBodyComponentAttribute(HttpContentType contentType = HttpContentType.Json) { ContentType = contentType; }