“package java.net.http does not exist” error on JDK9

匿名 (未验证) 提交于 2019-12-03 01:25:01

问题:

I have a problem compiling simple blocking GET example from the HttpRequest JavaDoc:

package org.example;  import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.http.HttpRequest; import java.net.http.HttpResponse;  import static java.net.http.HttpRequest.noBody; import static java.net.http.HttpResponse.asString;  public class Http2 {     public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException {         HttpResponse response = HttpRequest                 .create(new URI("http://www.infoq.com"))                 .body(noBody())                 .GET().response();         int responseCode = response.statusCode();         String responseBody = response.body(asString());          System.out.println(responseBody);     } } 

I'm getting package java.net.http does not exist error when compiling using JDK 9:

  

Same error occurs using command line and IntelliJ.

It is not a problem with my module because classes without java.net.http compiles and run without any problem.

Any idea what is going on?

回答1:

In your module definition, located (based on your package name) in src/org/example/module-info.java, you need to add the dependency to the java.net.http package, which is included in the java.httpclient module:

module org.example {     requires java.httpclient; } 

You can find the list of JDK modules in the module summary.



回答2:

Meanwhile, since build 149 of the jdk9, the classes

  • HttpClient
  • HttpRequest
  • HttpResponse
  • WebSocket

have been moved to the package jdk.incubator.http. They are part of the jigsaw module jdk.incubator.httpclient. See ticket JDK-8170648 for more details.

So you have to change your imports to jdk.incubator.http.*. Furthermore, you must include the module jdk.incubator.httpclient in your module-info.java. When compiling and running your code, add the argument --add-modules=jdk.incubator.httpclient to your invocation of the java and javac executables.

All classes related to the http client have been removed from jdk9. They are included as incubator features and are no longer part of the API. Hopefully, the new client will be part of jdk10.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!