我正在開發一個應用程序,用於遍歷一系列郵政編碼和業務類型,然後通過我構建的url創建對Google Places API(文本搜索)的調用這些參數。HttpWebResponse在Google Places API調用上超時
的網址就會是這個樣子
下面的函數被調用每一個請求:
private static StreamReader MakeWebRequest(string sURL)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sURL);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader objReader = new StreamReader(responseStream);
return objReader;
}
我遇到的問題是,經過3至5迭代,響應對象超時(System.Net.WebException =「操作已超時」)。我的第一個想法是,請求被髮送到很快,所以我在循環中插入了一個Sleep(2000),但這似乎沒有效果。我檢查了發生故障的網址,並將它們粘貼到瀏覽器中,然後做返回正確的數據。
據我所知,調用這個api的唯一限制是每天有1000個未經驗證的帳戶。我錯過了什麼?
編輯:這裏是程序塊的其餘部分:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using GooglePlacesJSONGenerator.Models;
namespace GooglePlacesJSONGenerator
{
class Program
{
static void Main(string[] args)
{
//set up a list of zips
List<string> zipcodeList = new List<string>();
zipcodeList.Add("57754");
zipcodeList.Add("57783");
zipcodeList.Add("57785");
//setup a list of business types
List<string> businessTypeList = new List<string>();
businessTypeList.Add("restaurants");
businessTypeList.Add("dentist");
businessTypeList.Add("gym");
//main data set
GooglePlaceDataSet places = new GooglePlaceDataSet();
//base url
string urlBase = "https://maps.googleapis.com/maps/api/place/textsearch/json?key=MY_API_KEY_HERE&sensor=false&query=";
string nextUrlBase = urlBase + "&pagetoken=";
Stream objStream;
//loop on zip codes
foreach (string zip in zipcodeList)
{
Console.WriteLine("looping on zip " + zip);
//loop on business type
foreach (string type in businessTypeList)
{
Console.WriteLine("loop on type " + type);
string sURL;
string query = HttpUtility.UrlEncode(zip + " " + type);
sURL = urlBase + query;
Console.WriteLine("Query String: " + query);
while (sURL != "")
{
Console.WriteLine("Our URL: " + sURL);
Console.WriteLine("");
StreamReader objReader = MakeWebRequest(sURL);
JsonTextReader reader = new JsonTextReader(objReader);
JsonSerializer se = new JsonSerializer();
string parsedData = se.Deserialize(reader).ToString();
GooglePlaceDataSet gSet = JsonConvert.DeserializeObject<GooglePlaceDataSet>(parsedData);
foreach (GooglePlaceData place in gSet.results)
{
places.results.Add(place);
}
if (gSet.next_page_token != null)
sURL = nextUrlBase + gSet.next_page_token;
else
sURL = "";
System.Threading.Thread.Sleep(2000);
}
}
}
Console.ReadLine();
}
你可以發佈你調用'MakeWebRequest'的代碼嗎? – dtsg 2012-07-17 15:44:37
這將是我的榮幸。 – seanicus 2012-07-17 15:50:52
嘗試取出'while(sURL!=「」)'並替換爲'if(!string.IsNullOrEmpty(sURL))'。你爲什麼使用while循環? – dtsg 2012-07-17 15:54:59