internal static string Write(Options options, HttpWebRequest request, string requestBody) { var output = new StringBuilder(); var oldColor = Console.ForegroundColor; if (request != null) { Console.ForegroundColor = ConsoleColor.Yellow; var line = string.Format("{0} {1} {2}/{3}", request.Method, request.RequestUri.PathAndQuery, (request.RequestUri.OriginalString.ToLower().Contains("https") ? Consts.HTTPS : Consts.HTTP), request.ProtocolVersion ); output.Append(line); Console.WriteLine(line); Console.WriteLine(); if (options.ShowHeaders) { for (int idx = 0; idx < request.Headers.Count; idx++) { var key = request.Headers.GetKey(idx); var val = request.Headers[idx]; output.Append(WriteColored(key, val)); } } if (options.ShowBody) { if (request.ContentType == "application/json") { var obj = JObject.Parse(requestBody); output.Append(WriteJsonTree(obj, 1)); } else { Console.ForegroundColor = oldColor; output.Append(requestBody); Console.WriteLine(requestBody); } } } output.Append(Environment.NewLine + Environment.NewLine); Console.WriteLine(); Console.WriteLine(); Console.ForegroundColor = oldColor; return output.ToString(); }
public HttpWebResponse GetResponse(Options args) { var url = args.Item.Url; if (args.Item.QueryStringParameters != null) { string data = args.Item.QueryStringParameters.Aggregate("", (current, paramter) => current + ("&" + paramter)); if (!string.IsNullOrEmpty(data)) { if (!url.Contains('?')) { url += "?" + data.Remove(0, 1); } else { url += data; } } } this.Request = WebRequest.Create(url) as HttpWebRequest; this.Request.Method = args.Item.Method; // Adding headers bool acceptSetExplicit = false; bool contentTypeSetExplicit = false; if (args.Item.Headers != null) { foreach (var header in args.Item.Headers) { var el = header.Split(':'); if (el.Length == 2) { var key = el[0]; if (key.Equals("User-Agent", StringComparison.OrdinalIgnoreCase)) { this.Request.UserAgent = el[1]; } else if (key.Equals("Accept", StringComparison.OrdinalIgnoreCase)) { this.Request.Accept = el[1]; acceptSetExplicit = true; } else if (key.Equals("Content-Type", StringComparison.OrdinalIgnoreCase)) { this.Request.ContentType = el[1]; contentTypeSetExplicit = true; } else { this.Request.Headers.Add(el[0], el[1]); } } } } // Adding Files if (args.Item.Files != null) { string formDataBoundary = string.Format("----------{0:N}", Guid.NewGuid()); string contentType = "multipart/form-data; boundary=" + formDataBoundary; var postParameters = new Dictionary<string, object>(); foreach (var fileParam in args.Item.Files) { var fileInfo = fileParam.Split('@'); if (fileInfo.Length == 2) { byte[] fileContent = null; try { fileContent = File.ReadAllBytes(fileInfo[1]); } catch { } if (fileContent != null) { postParameters.Add(fileInfo[0], new FileParameter(fileContent, Path.GetFileName(fileInfo[1]), GetContentTypeOfFile(Path.GetExtension(fileInfo[1])))); } } } if (args.Item.Paramters != null) { foreach (var paramter in args.Item.Paramters) { var item = paramter.Split('='); if (item.Length == 2) postParameters.Add(item[0], item[1]); } } byte[] formData = GetMultipartFormData(postParameters, formDataBoundary); this.Request.Method = Consts.HTTP_POST; this.Request.ContentType = contentType; this.Request.ContentLength = formData.Length; using (var requstStream = this.Request.GetRequestStream()) { requstStream.Write(formData, 0, formData.Length); requstStream.Close(); } this.RequestBody = Encoding.UTF8.GetString(formData); } // Adding Parameters else if (this.Request.Method == Consts.HTTP_POST || this.Request.Method == Consts.HTTP_PUT) { if (args.Item.Paramters != null) { if (this.Request.Method == Consts.HTTP_POST) { if (args.UseForm) { if (!contentTypeSetExplicit) this.Request.ContentType = FORM; if (!acceptSetExplicit) this.Request.Accept = "*/*"; } else { if (!contentTypeSetExplicit) this.Request.ContentType = JSON; if (!acceptSetExplicit) this.Request.Accept = "application\\json"; } } else if (this.Request.Method == Consts.HTTP_PUT) { if (!acceptSetExplicit) this.Request.Accept = "*/*"; } else { if (!contentTypeSetExplicit) this.Request.ContentType = JSON; if (!acceptSetExplicit) this.Request.Accept = "application\\json"; } if (args.UseForm) { byte[] postFormData = null; string formData = args.Item.Paramters.Aggregate("", (x, p) => x + ("&" + p)); if (!string.IsNullOrEmpty(formData)) { formData = formData.Remove(0, 1); postFormData = Encoding.UTF8.GetBytes(formData); } if (postFormData != null) { this.Request.ContentLength = postFormData.Length; using (var dataStream = this.Request.GetRequestStream()) { dataStream.Write(postFormData, 0, postFormData.Length); } this.RequestBody = Encoding.UTF8.GetString(postFormData); } } else { var tempList = args.Item.Paramters.Select(p => p.Split('=')).ToDictionary<string[], string, object>(el => el[0], el => el[1]); var jsonData = JsonConvert.SerializeObject(tempList); byte[] postJsonData = Encoding.UTF8.GetBytes(jsonData); this.Request.ContentLength = postJsonData.Length; using (var dataStream = this.Request.GetRequestStream()) { dataStream.Write(postJsonData, 0, postJsonData.Length); } this.RequestBody = Encoding.UTF8.GetString(postJsonData); } } else { // No Data to send if (args.UseJson) { if (!acceptSetExplicit) this.Request.Accept = "application\\json"; if (!contentTypeSetExplicit) this.Request.ContentType = null; } if (args.UseForm) { if (!contentTypeSetExplicit) this.Request.ContentType = FORM; } } } /// Set Cookies // TODO //this.Request.CookieContainer = new CookieContainer(); // Setting defaults if (string.IsNullOrEmpty(this.Request.UserAgent)) this.Request.UserAgent = "HTTPie.net/" + BuildConsts.MAIN_VERSION; if (string.IsNullOrEmpty(this.Request.Headers[HttpRequestHeader.AcceptEncoding])) this.Request.Headers.Add(HttpRequestHeader.AcceptEncoding, "identity, defalte, compress, gzip"); if (args.Item.Timeout > 0) this.Request.Timeout = args.Item.Timeout; if (string.IsNullOrEmpty(this.Request.Accept)) { this.Request.Accept = "*/*"; } // Execute the Request var response = this.Request.GetResponse(); return response as HttpWebResponse; }
internal static string Write(Options options, RunResult result, HttpWebResponse response) { var output = new StringBuilder(); var oldColor = Console.ForegroundColor; if (result.ResponseCode != 0 && response == null) { Console.ForegroundColor = ConsoleColor.Red; var line = string.Format("ERROR {0} {1} ", options.Item.Url, result.ResponseCode ); output.Append(line); Console.Write(line); } if (response != null) { Console.ForegroundColor = ConsoleColor.Yellow; var line = string.Format("{0}/{1} {2} ", (response.ResponseUri.OriginalString.ToLower().Contains("https") ? Consts.HTTPS : Consts.HTTP), response.ProtocolVersion, result.ResponseCode ); Console.Write(line); output.Append(line); Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine(response.StatusDescription); output.Append(response.StatusDescription + Environment.NewLine); if (options.ShowHeaders) { foreach (string header in response.Headers) { output.Append(WriteColored(header, response.GetResponseHeader(header))); } } if (options.ShowBody) { if (response.ContentType == "application/json") { var obj = JObject.Parse(result.ResponseBody); output.Append(WriteJsonTree(obj, 1)); } else { Console.ForegroundColor = oldColor; output.Append(result.ResponseBody + Environment.NewLine); Console.WriteLine(result.ResponseBody); } } } Console.ForegroundColor = oldColor; return output.ToString(); }