public async Task <bool> FireAPISeachRequest() { bool _b_Result = false; try { if (this._mEn_RequestState != GoogleSearchAPIRequestState.Ready) { throw new Exception("Request has already been fired with this instance"); } if (this._mStr_SearchTerms == null) { throw new Exception("Search terms can not be NULL"); } // Instantiating object of HttpClient HttpClient _obj_HttpClient = new HttpClient(); // Setting base URL for HttpClient object to Google Custom Search API's url _obj_HttpClient.BaseAddress = new Uri(ConfigurationManager.AppSettings["GoogleCustomSearchAPIUrl"]); //_obj_HttpClient.BaseAddress = new Uri(GoogleSearchAPIRequestUrl.APIRequestUrl()); _obj_HttpClient.DefaultRequestHeaders.Accept.Clear(); // Set time out length for request TimeSpan _obj_TmSpn = new TimeSpan(0, 0, 0, 30, 0); _obj_HttpClient.Timeout = _obj_TmSpn; // Setting request mode is now in requesting this._mEn_RequestState = GoogleSearchAPIRequestState.Requesting; // Firing asynchronus request to Google HttpResponseMessage _obj_Response = await _obj_HttpClient.GetAsync( "?key=" + ConfigurationManager.AppSettings["GoogleCustomSearchAPIKey"] + "&q=" + HttpUtility.UrlEncode(_mStr_SearchTerms) + "&cx=" + ConfigurationManager.AppSettings["GoogleCustomSearchAPICX"] + "&start=" + _mInt_StartIndex.ToString() + "&googlehost=google.com.au"); if (_obj_Response != null && _obj_Response.IsSuccessStatusCode) { // Response is fully consumed by program and in state ready to be returned to the user! _mStr_Response = await _obj_Response.Content.ReadAsStringAsync(); this._mEn_RequestState = GoogleSearchAPIRequestState.ResponseComplete; _b_Result = true; } else { throw new Exception("Request to Google Custom Search API failed"); } } catch (Exception e) { this._mEn_RequestState = GoogleSearchAPIRequestState.Error; this._mStr_SearchError = e.Message; } // return the overal result of the attempted request return(_b_Result); }
public GoogleSearchAPIRequest(string str_SearchTerms, int int_StartIndex) { this._mEn_RequestState = GoogleSearchAPIRequestState.Ready; this._mStr_SearchTerms = str_SearchTerms; this._mInt_StartIndex = int_StartIndex; }