简体   繁体   English

Java-HttpURLConnection到立交服务器

[英]Java - HttpURLConnection to overpass server

I am trying to build up a server connection to overpass with Java. 我正在尝试建立服务器连接以使用Java进行立交桥。 But I always get a bad request response when there is a white space in my request parameter like Bulach West . 但是,当我的请求参数中有空白(例如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 最好的问候,纳扎尔

我认为您必须像这样编码字符串参数如何编码url参数

Thanks for help m8. 感谢您的帮助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. 起初,我试图用java类URLEncoder编码我的网址,而是因为“[\\‘\\某些特定字符的铁路\\’= \\‘tram_stop \\’]编码的结果是不正确的。

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;) 因此,我要做的是复制一个示例网址,例如( 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. 发送请求并获得正确的响应后,我从Web浏览器复制了链接并将其添加到我的Java代码中。 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 ;) 现在看起来像:( http://www.overpass-api.de/api/interpreter?data[ out: xml];node[%22highway%22=%22bus_stop%22[%22name%22%20=%20 %22Bulach + West%22]; out ;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM