Google Webservice Problem
Hi, I am new to the forums here and was hoping someone could help me out. I have been working on this project and have been stuck for quite a while now(almost a week). I am learning about how to connect java to the web and would like to do the example of connecting to a google webservice. (specifically the geocoding webservice) I have created a valid URL I know because it works in the browser, but I just get a thrown exception (http 400---bad request) when I try to call upon the URL from my java code.
Thanks in advance for any help. I'm truly stumped!
Jim
Code java:
private void searchGoogle(String street, String city, String state)
{
URL url = null;
URLConnection connection = null;
InputSource inputxml = null;
NodeList nodes = null;
Permission per= null;
//run a search on google server and display results in list
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
//replace all spaces in search strings with "+"
street.replace(' ', '+');
city.replace(' ', '+');
state.replace(' ', '+');
String request = "http://maps.googleapis.com/maps/api/geocode/xml?address=";
request = request.concat(street);
request = request.concat(",+");
request = request.concat(city);
request = request.concat(",+");
request = request.concat(state);
request = request.concat("&sensor=false");
try
{
url = new URL(request);
connection = url.openConnection();
inputxml = new InputSource(connection.getInputStream());
nodes = (NodeList) xpath.evaluate("XPATH_EXPRESSION", inputxml, XPathConstants.NODESET);
}
catch(Exception MalformedURLException){
System.out.print("connection error");
}
// We can then iterate over the NodeList and extract the content via getTextContent().
// NOTE: this will only return text for element nodes at the returned context.
for (int i = 0, n = nodes.getLength(); i < n; i++) {
String nodeString = nodes.item(i).getTextContent();
System.out.print(nodeString);
System.out.print("\n");
}
}
Re: Google Webservice Problem
First, be sure you are not violating the google terms of use. Second, set the User-Agent request property for the URLConnection. I cannot recall the exact code, but something like:
Code :
connection.setRequestProperty("User-Agent", "Mozilla 6.0");
Again, not sure if the above will work but you should be able to find several examples with a google search on how to set the user agent. Lastly, be sure you are not violating the google terms of use.