400 错误 Docker 容器与 HTTPURLConnection 之间的 HTTP GET 请求



我在docker-compose文件中定义了两个容器:


tomcat_webserver_api:
image: tomcat:8
volumes:
- ./API/Docker/API.war:/usr/local/tomcat/webapps/API.war
ports:
- "8080:8080"
depends_on:
- mysql_database
tomcat_webserver_anwendung:
image: tomcat:8
ports:
- "8081:8080"
volumes:
- ./Anwendung/Docker/Anwendung.war:/usr/local/tomcat/webapps/Anwendung.war
depends_on:
- tomcat_webserver_api
environment:
API_HOST: tomcat_webserver_api
API_PORT: 8080

现在我想使用 HttpURLConnection 从 Java Web 应用程序内部访问 URLhttp://tomcat_webserver_api:8080/API/restaurants/Wochentag

问题:它返回 400 错误

java.io.IOException: Server returned HTTP response code: 400 for URL: http://tomcat_webserver_api:8080/API/restaurants/Wochentag

代码是这样的(当我尝试通过 curl 连接到 URL 时,标头几乎相同 - 这在容器内工作,呵呵(:


URL api = UriBuilder.fromUri("http://" + "tomcat_webserver_api" + ":" + "8080" +"/API/restaurants/RestaurantSpeisen").build().toURL();
System.setProperty("http.agent", "curl/7.52.1");
HttpURLConnection connection = (HttpURLConnection) api.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Host", "localhost");
connection.setRequestProperty("User-Agent", "curl/7.52.1");
connection.connect();
BufferedReader in = new BufferedReader(new             InputStreamReader(connection.getInputStream(), "UTF-8"));

如果我尝试连接到http://172.20.0.3:8080/API/restaurants/Wochentag我得到了一个 200 ok HTTP 响应代码和 JSON 数据。

如果我执行 API 容器并检查日志,我可以看到 400 个 GET 请求。

为什么会这样?

http://172.20.0.3:8080/API/restaurants/Wochentag- 作品http://tomcat_webserver_api:8080/API/restaurants/Wochentag- 不起作用,但不会出现 404 错误

我遇到了与您相同的问题,显然下划线不允许作为虚拟主机,请尝试将其删除,例如,仅使用tomcatwebserverapi,这应该可以解决您的问题。

请参阅(域名(子域中是否有下划线"_"?,了解有关主机名中有效字母的更多信息。

请尝试显式容器名称:

tomcat_webserver_api:
image: tomcat:8
container_name: tomcat_webserver_api
volumes:
- ./API/Docker/API.war:/usr/local/tomcat/webapps/API.war
ports:
- "8080:8080"
depends_on:
- mysql_database
tomcat_webserver_anwendung:
container_name: tomcat_webserver_app
image: tomcat:8
ports:
- "8081:8080"
volumes:
- ./Anwendung/Docker/Anwendung.war:/usr/local/tomcat/webapps/Anwendung.war
depends_on:
- tomcat_webserver_api
environment:
API_HOST: tomcat_webserver_api
API_PORT: 8080

"仅本地"配置需要显式容器名称来激活 Docker 的名称查找机制。在 Swarm 模式下,无需设置容器名称。

最新更新