我正在尝试使用HttpClient从Google Places Api获取餐馆列表。
此代码获得状态为OK的响应:
public async Task<HttpResponseMessage> Get(Location location)
{
using (var client = new HttpClient())
{
var response = await
client.GetAsync(
$"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={location.lat},{location.lng}&radius=500&types=food&key={apiKey}");
return response;
}
}
然后,将相同的URL粘贴到Postman中,可以获得我想要的JSON。 例如:
{
"html_attributions": [],
"next_page_token": "CoQC8QAAAHJGK9M9kkDpmZs3UdDzT5KnypEqb4fdMoXeUFO836ks9B-wyE2GWs3a4xbuH_NvbbsQFELL4DoMl9Q7q2f28_6XtKVS3V0xKbDEMAdczLcauQrf3vNE0cIprK2DYemtJMowngp9Wu_3WSRDrxoP2BiWJbsqYk5okWPnPp3PM4cBjdE3f5sFkV3LCKOwdSChXT7a-fmy6katMS30vdqT5Jr4V0X3XeaFGJQvVWgiyHXjJKIQZRtZKbxr9ovT-B4uezbtV2-8NDoUXAZO0R2eBkrCWPlW_p8nnVYGilHpvvTk1V9WbXQfwm09y2SODZghVOuX7ViwqfM_s-1HOWZGjrkSEKpA1NwbMuLrtGvxqrVnTjsaFNjbcDsEdX_JkwhkrAi2hBwPzXNU",
"results": [
{
"geometry": {
"location": {
"lat": 55.701531,
"lng": 13.192277
}
},
"icon": "https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
"id": "3af0d044d45cd8587d9a3522bc98a95d4f60c6a8",
"name": "Restaurang Stäket",
"opening_hours": {
"open_now": false,
"weekday_text": []
},
"photos": [
{
"height": 333,
"html_attributions": [
"<a href=\"https://maps.google.com/maps/contrib/107255944189419980694\">Restaurang Stäket</a>"
],
"photo_reference": "CmRdAAAAvIl4I9qTovKy3a66JJ--SUePUSoP4vE54BBuf6YIzJkfEzWxEVnx6RdoPp7kQ1O5rm8w0gTVYatE5RJg5gc98S92g7pV7JqKQtGf_-ny1a3kAjBl7NO9qoI7AwLeXiW0EhB2BLJoKLHYWZozRi_FgfhMGhRDnPbNeAyi17Kt-anIZgOAY-7rRQ",
"width": 331
}
],
"place_id": "ChIJfc06o8SXU0YRqQzS2ENuF84",
"rating": 3.8,
"reference": "CnRmAAAAb04Z5F5nUHFRqqOxKPgJ6gBzJ-sDq21h6VE4gSVIAIAk5SCNzBac6N8_U3ozbh5Re-eEmqhseFnxAwzZjUNRGYSTG85rvXe6EBXJjz3xFtLZhp-dzezLNUgm6znBewmLsEBea5jTCB8Lyd3y4kz3lBIQOXYJ96C2SITtKUYNffZDOhoU-wLLrXGXdXb-AYigiG6jqGPgp8s",
"scope": "GOOGLE",
"types": [
"restaurant",
"food",
"point_of_interest",
"establishment"
],
"vicinity": "Stora Södergatan 6, Lund"
}
],
"status": "OK"
}
但是,当尝试在响应中获取内容的字符串表示时,如下所示:
public async Task<string> Get(Location location)
{
using (var client = new HttpClient())
{
var response = await
client.GetAsync(
$"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={location.lat},{location.lng}&radius=500&types=food&key={apiKey}");
return await response.Content.ReadAsStringAsync();
}
}
我得到了这个:
{
"html_attributions" : [],
"results" : [],
"status" : "INVALID_REQUEST"
}
如果我检查响应对象,状态代码仍然正常,所以API请求似乎没问题,但是当我试图获取时,我无法弄清楚出了什么问题。字符串。