public string HttpPost(string url, string strJson) { string result = ""; try { if (!IsInternet) { ResponseData responseData = new ResponseData(); responseData.result = ""; responseData.message = "当前不存在网络,请使用离线模式。"; return(JsonHelper.Serialize(responseData)); } HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); Stream dataStream = null; request.Method = Method; request.ContentType = ContentType; if (!string.IsNullOrEmpty(TGT)) { request.Headers.Add("Cookie", TGT); } request.Timeout = this.TimeOut; request.ReadWriteTimeout = this.ReadWriteTimeout; request.MaximumAutomaticRedirections = 100; byte[] bytes = Encoding.UTF8.GetBytes(strJson); using (dataStream = request.GetRequestStream()) { dataStream.Write(bytes, 0, bytes.Length); } var response = (HttpWebResponse)request.GetResponse(); ResponseExceptionBase responseExceptionBase = new ResponseExceptionBase(response.StatusCode); if (responseExceptionBase.IsSuccess) { using (var stream = response.GetResponseStream()) { var resultBuffer = this.GetResponseBuffter(stream); result = ResponseEncoding.GetString(resultBuffer); } } response.Close(); if (!responseExceptionBase.IsSuccess) { return(null); } return(result); } catch (Exception ex) { ResponseData responseData = new ResponseData(); responseData.result = "1111"; responseData.message = ex.Message; return(JsonHelper.Serialize(responseData)); } }
public string GetBodyString() { byte[] bytes = GetBodyBytes(); if (bytes == null || bytes.Length < 1) { return(string.Empty); } return(ResponseEncoding.GetString(bytes)); }
public string GetResponseBodyAsString() { if (!RequestLocked) { throw new Exception("You cannot call this function before request is made to server."); } GetResponseBody(); return(ResponseBodyString ?? (ResponseBodyString = ResponseEncoding.GetString(ResponseBody))); }
/// <summary> /// Requests questions from the API. /// </summary> /// <param name="amount">The amount of questions to request.</param> /// <param name="category">The category of the questions. If left empty the questions will have mixed categories.</param> /// <param name="difficulty">The difficulty of the questions. Easy, Medium, or Hard. If left empty the questions received will have mixed difficulty levels.</param> /// <param name="type">The type of questions. Multiple or Boolean. If left empty the questions will have mixed types.</param> /// <param name="encoding">The type of encoding used in the response. Default, urlLegacy, url3986, or base64. If left empty it will use the default encoding (HTML Codes).</param> /// <param name="sessionToken">A session token. This token prevents the API from giving you the same question twice until 6 hours of inactivity or you reset the token.</param> /// <returns>A <see cref="QuestionsResponse"/> object.</returns> /// <exception cref="System.ArgumentOutOfRangeException">Thrown when <paramref name="amount"/> is out of range.</exception> public static QuestionsResponse RequestQuestions(uint amount, QuestionCategory category = QuestionCategory.Any, QuestionDifficulty difficulty = QuestionDifficulty.Any, QuestionType type = QuestionType.Any, ResponseEncoding encoding = ResponseEncoding.Default, string sessionToken = "") { string json; using (var wc = new WebClient()) { json = wc.DownloadString(GenerateApiUrl(amount, category, difficulty, type, encoding, sessionToken)); } return(JsonConvert.DeserializeObject <QuestionsResponse>(json)); }
public void SetResponseBodyString(string body) { if (!RequestLocked) { throw new Exception("You cannot call this function before request is made to server."); } if (ResponseBody == null) { GetResponseBody(); } var bodyBytes = ResponseEncoding.GetBytes(body); SetResponseBody(bodyBytes); }
private void ReadText(Stream stream, Byte[] bytes) { String CurrentLine = ""; Byte[] bb = null; StringReader sr = new StringReader(this.ResponseEncoding.GetString(bytes)); while (true) { CurrentLine = sr.ReadLine(); if (CurrentLine == null) { break; } bb = ResponseEncoding.GetBytes(CurrentLine + MailParser.NewLine); stream.Write(bb, 0, bb.Length); } }
private void ReadText(Stream stream, Byte[] bytes) //I duota streama uzraso baitu array { String CurrentLine = ""; //+ Byte[] bb = null; //+ StringReader sr = new StringReader(this.ResponseEncoding.GetString(bytes)); //String readeris su uzkoduotu bytes array while (true) { CurrentLine = sr.ReadLine(); //+ if (CurrentLine == null) { break; } //+ bb = ResponseEncoding.GetBytes(CurrentLine + MailParser.NewLine); //+ stream.Write(bb, 0, bb.Length); //Raso i streama duomenys } }
public static string GenerateApiUrl(uint amount, QuestionCategory category = QuestionCategory.Any, QuestionDifficulty difficulty = QuestionDifficulty.Any, QuestionType type = QuestionType.Any, ResponseEncoding encoding = ResponseEncoding.Default, string sessionToken = "") { if (amount < 1 || amount > 50) { throw new ArgumentOutOfRangeException(nameof(amount), amount, "Amount must be between 1 and 50."); } string query = $"amount={amount}"; if (category != QuestionCategory.Any) { query += $"&category={category:D}"; } if (difficulty != QuestionDifficulty.Any) { query += $"&difficulty={difficulty.ToString().ToLowerInvariant()}"; } if (type != QuestionType.Any) { query += $"&type={type.ToString().ToLowerInvariant()}"; } if (encoding != ResponseEncoding.Default) { query += $"&encode={encoding}"; } if (!string.IsNullOrEmpty(sessionToken)) { query += $"&token={sessionToken}"; } return($"{ApiEndpoint}?{query}"); }
/** Public methods **/ public QuestionsResponse RequestQuestions(uint amount, QuestionDifficulty difficulty = QuestionDifficulty.Undefined, QuestionType type = QuestionType.Undefined, ResponseEncoding encoding = ResponseEncoding.Undefined, uint categoryID = 0, string sessionToken = "") { string Url = "https://opentdb.com/api.php?amount=" + amount; if (categoryID != 0) { Url += "&category=" + categoryID; } if (difficulty != QuestionDifficulty.Undefined) { Url += "&difficulty=" + difficulty.ToString().ToLower(); } if (type != QuestionType.Undefined) { Url += "&type=" + type.ToString().ToLower(); } if (encoding != ResponseEncoding.Undefined) { Url += "&encode=" + encoding.ToString(); } if (sessionToken != "") { Url += "&token=" + sessionToken; } string JsonString = SendAPIRequest(Url); return(JsonConvert.DeserializeObject <QuestionsResponse>(JsonString)); }
public void Run(ref CookieContainer cookies) { _request = (HttpWebRequest)WebRequest.Create(Address); _request.Method = "POST"; _request.Host = Host; _request.Headers.Add("DNT", "1"); _request.Proxy = Proxy; _request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; if (TimeOut > 0) { _request.Timeout = TimeOut; _request.ReadWriteTimeout = TimeOut; } else { _request.Timeout = 90000; _request.ReadWriteTimeout = 90000; } // if (NoCachePolicy == false) // { var noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore); _request.CachePolicy = noCachePolicy; // } if (Expect100Continue == true) { _request.ServicePoint.Expect100Continue = true; } else { _request.ServicePoint.Expect100Continue = false; } _request.ContentType = ContentType; _request.Accept = Accept; _request.Referer = Referer; _request.KeepAlive = KeepAlive; // _request.KeepAlive = true; foreach (KeyValuePair <string, string> keyValuePair in Headers) { _request.Headers.Add(keyValuePair.Key, keyValuePair.Value); } _request.CookieContainer = cookies; if (UserAgent == null) { _request.UserAgent = Dom.Catalog.Data.Ie11; } else { _request.UserAgent = UserAgent; } if (AllowAutoRedirect != null) { _request.AllowAutoRedirect = (bool)AllowAutoRedirect; } byte[] sentData; if (ByteData != null) { sentData = ByteData; } else { sentData = Encoding.UTF8.GetBytes(Data); } _request.ContentLength = sentData.Length; Stream sendStream = _request.GetRequestStream(); sendStream.Write(sentData, 0, sentData.Length); sendStream.Close(); WebResponse response = _request.GetResponse(); ResponseHeaders = response.Headers; RequestHeaders = _request.Headers; Stream stream = response.GetResponseStream(); if (stream != null) { if (ResponseEncoding.IsEmpty()) { Response = new StreamReader(stream).ReadToEnd(); } else { Response = new StreamReader(stream, Encoding.GetEncoding(ResponseEncoding)).ReadToEnd(); } } response.Close(); }
/// <summary> /// Retrieves random <see cref="TriviaQuestion"/>. /// </summary> /// <param name="amount"> /// Amount of questions to be retrieved. /// </param> /// <param name="category"> /// Category of the questions to be retrieved. /// </param> /// <param name="type"> /// Type of the questions to be retrieved. /// </param> /// <param name="difficulty"> /// Difficulty of the questions to be retrieved. /// </param> /// <param name="encoding"> /// Encoding of the API response to be used. /// </param> /// <param name="sessionToken"> /// Session token to be used. /// </param> /// <returns> /// Array of <see cref="TriviaQuestion"/> based on specified parameters. /// </returns> /// <exception cref="OpenTriviaException"> /// Unexpected error occured. /// </exception> /// <exception cref="HttpRequestException"> /// The request failed due to an underlying issue such as network connectivity, DNS /// failure, server certificate validation or timeout. /// </exception> /// <exception cref="JsonException"> /// The JSON is invalid. /// </exception> public async Task <TriviaQuestion[]> GetQuestionAsync(byte amount = 10, Category category = Category.Any, TriviaType type = TriviaType.Any, Difficulty difficulty = Difficulty.Any, ResponseEncoding encoding = ResponseEncoding.Default, string sessionToken = "") { if (amount <= 0) { amount = 1; } else if (amount > 50) // hard limit { amount = 50; } var url = new StringBuilder(this._BaseApiUrl + $"amount={ amount }"); if (category != Category.Any) { url.Append($"&category={ (byte)category }"); } if (difficulty != Difficulty.Any) { url.Append($"&difficulty={ difficulty.ToString().ToLower() }"); } if (type != TriviaType.Any) { url.Append($"&type={ type.ToString().ToLower() }"); } if (encoding != ResponseEncoding.Default) { url.Append($"&encode={ encoding.ToString().ToLower() }"); } if (sessionToken != "") { url.Append($"&token={ sessionToken }"); } else { if (this._SessionToken != "") { url.Append($"&token={ this._SessionToken }"); } } using (var doc = await this.GetJsonResponseAsync <JsonDocument>(url.ToString())) { var responseCode = doc.RootElement.GetProperty("response_code").GetByte(); if (responseCode != 0) { throw new OpenTriviaException(this.ResponseError(responseCode)); } var jsonArray = doc.RootElement.GetProperty("results"); var questions = new List <TriviaQuestion>(); if (encoding == ResponseEncoding.Default) { foreach (var item in jsonArray.EnumerateArray()) { questions.Add(this.ReadTriviaQuestion(item)); } } else if (encoding == ResponseEncoding.Url3986) { foreach (var item in jsonArray.EnumerateArray()) { questions.Add(this.ReadTriviaQuestionURL(item)); } } else { foreach (var item in jsonArray.EnumerateArray()) { questions.Add(this.ReadTriviaQuestionBase64(item)); } } return(questions.ToArray()); } }
public string HttpGet(string url, IDictionary <string, string> queryStrings = null) { string result = ""; try { string fullUrl = url; if (queryStrings != null) { StringBuilder sb = new StringBuilder(); foreach (var query in queryStrings) { if (query.Value != null) { sb.Append(string.Format("&{0}={1}", query.Key, query.Value)); } } if (sb.Length > 0) { fullUrl = string.Format("{0}?{1}", url, sb.ToString().Trim('&')); } } HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(fullUrl); request.Method = Method; request.ContentType = ContentType; if (!string.IsNullOrEmpty(TGT)) { if (TGT.Contains("CASTGC")) { request.Headers.Add("Cookie", TGT); } else { request.Headers.Add("TGT", TGT); } } request.Timeout = this.TimeOut; request.ReadWriteTimeout = this.ReadWriteTimeout; request.MaximumAutomaticRedirections = 100; var response = (HttpWebResponse)request.GetResponse(); ResponseExceptionBase responseExceptionBase = new ResponseExceptionBase(response.StatusCode); if (responseExceptionBase.IsSuccess) { using (var stream = response.GetResponseStream()) { var resultBuffer = this.GetResponseBuffter(stream); result = ResponseEncoding.GetString(resultBuffer); } } response.Close(); if (!responseExceptionBase.IsSuccess) { return(null); } } catch (Exception ex) { throw ex; } return(result); }
public void QuestionsNotEmptyTest(uint amount, QuestionCategory category, QuestionDifficulty difficulty, QuestionType type, ResponseEncoding encoding) { // Act var response = TriviaApi.RequestQuestions(amount, category, difficulty, type, encoding); // Assert Assert.NotEmpty(response.Questions); }