Java - HttpURLConnection to overpass server

349 views Asked by At

I am trying to build up a server connection to overpass with Java. But I always get a bad request response when there is a white space in my request parameter like Bulach West. The code I used is following:

StringBuilder content = new StringBuilder();

URL url = new URL("http://www.overpass-api.de/api/interpreter?data=[out:xml];node[\"railway\"=\"tram_stop\"][\"name\" = \"Bulach West\"];out;");

HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
System.out.println("Content-Type: " +urlConnection.getContentType());
System.out.println("Content-Length: " + urlConnection.getContentLength());
System.out.println( "Date: " +new Date(urlConnection.getDate()));
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;

urlConnection.connect();

while ((line = bufferedReader.readLine()) != null) {
       content.append(line + "\n");
}
bufferedReader.close();
 System.out.println("output:\n "+content); 

Requests without whitespaces work fine. What can I do now? Best regards, Nazar

2

There are 2 answers

0
Zavael On

I think you have to encode the string parameter like here How do I encode url parameters

0
Nazar Medeiros On

Thanks for help m8. I found a working solution.

At first I tried to use the java class URLEncoder to encode my url, but because of some specific characters like \" in [\"railway\"= \"tram_stop\"] the encoded result was not correct.

So what I did is to copy an example url like (http://www.overpass-api.de/api/interpreter?data=[out:xml];node[\"railway\"=\"tram_stop\"][\"name\" = \"Bulach West\"];out;)

and pass this into my web browser. After sending the request and getting a correct response, I copied the link from my web browser and added it into my java code. Sending the request encoded my url automatically.

Now it looks like: (http://www.overpass-api.de/api/interpreter?data[out:xml];node[%22highway%22=%22bus_stop%22[%22name%22%20=%20%22Bulach+West%22];out;)