JAVA9 Http2使用

项目结构目录如下图

创建一个测试类 Http2Example01 代码如下

package http2.com.http2.example01;

import jdk.incubator.http.HttpClient;
import jdk.incubator.http.HttpRequest;
import jdk.incubator.http.HttpResponse;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * @author:CrazyShaQiuShi
 * @email:[email protected]
 * @descript:
 * @version:1.0.0
 */
public class Http2Example01 {
    public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException {
        HttpClient httpClient = HttpClient.newHttpClient();
        HttpResponse httpResponse = httpClient.send(
                HttpRequest
                        .newBuilder(new URI("http://transport.opendata.ch/v1/connections?from=Bern&to=z%C3%BCrich&datetime=2017-09-21T17%3A00")
                        ).GET().build(),
                HttpResponse.BodyHandler.asString()
        );
        int code = httpResponse.statusCode();
        System.out.println(code);
        System.out.println(httpResponse.body().toString());
    }
}

运行后发现报如下错误

这是由于java9采用模块化,所以你需要在目录中新建一个名称为 module-info.java 的文件。并在该文件中引用相关模块

添加代码如下

module  http2{
    requires jdk.incubator.httpclient;
    exports http2.com.http2.example01;
}

结果:

你可能感兴趣的:(java)