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

问题描述 投票:0回答:2

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

 
 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应用程序内部访问URL http://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时,Headers几乎相同 - 这在容器内部工作):


    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-Data。

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

为什么会这样?

http://172.20.0.3:8080/API/restaurants/Wochentag - 工作http://tomcat_webserver_api:8080/API/restaurants/Wochentag - 无法工作,但没有404错误

api docker tomcat docker-compose tomcat8.5
2个回答
2
投票

我遇到了和你一样的问题,显然下划线不允许作为虚拟主机,尝试删除它,例如,只使用tomcatwebserverapi,这应该可以解决你的问题。

有关主机名中有效字母的更多信息,请参阅Can (domain name) subdomains have an underscore "_" in it?


0
投票

请尝试使用明确的容器名称:

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模式下,您不需要设置容器名称。

© www.soinside.com 2019 - 2024. All rights reserved.