我正在尝试从 Google Places API 获取签到位置,但是当我尝试通过 url.openStream() 读取 XML FileNotFoundException 时出现错误。我的密钥是正确的,因为我尝试在浏览器的其他 URL 中使用它。如果有人使用过此功能,请告诉我如何操作。这是我的代码:
public String checkingMessage()
{
String strURL = "https://maps.googleapis.com/maps/api/place/check-in/xml?sensor=true&key=" + GOOGLE_API_KEY;
URL url;
try
{
url = new URL(strURL.replace(" ", "%20"));
// Standard of reading a XML file
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder;
Document doc = null;
XPathExpression expr = null;
builder = factory.newDocumentBuilder();
doc = builder.parse(new InputSource(url.openStream()));
// Create a XPathFactory
XPathFactory xFactory = XPathFactory.newInstance();
// Create a XPath object
XPath xpath = xFactory.newXPath();
// Compile the XPath expression
expr = xpath.compile("//reference/text()");
// Run the query and get a nodeset
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
String answer = nodes.item(0).getNodeValue();
Toast.makeText(getApplicationContext(), answer, Toast.LENGTH_LONG);
}catch(Exception ex){
ex.printStackTrace();
}
return null;
}
如果我在浏览器中使用直接 url,我会收到以下错误:
400: Your client has issued a malformed or illegal request. That’s all we know.
我不知道 json 解析,所以我使用的是 XML。我认为输出应该是这样的,因此我试图获取参考值:
<CheckInRequest>
<reference>place_reference</reference>
</CheckInRequest>
更新:我尝试使用 HttpResponse 并获得对 Entity 的响应,如下所示
if (httpResponse.getStatusLine().getStatusCode() == 200){
strResult = EntityUtils.toString(httpResponse.getEntity());
}
但后来我得到 MalFormedException
doc = builder.parse(strResult); // doc is Document type
无论哪种方式,我怎样才能将 xml 结果放入 doc