JAVA9 Http2使用

项目结构目录如下图

《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:3105334046@qq.com * @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 Http2使用》

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

添加代码如下

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

结果:

《JAVA9 Http2使用》

    原文作者:CrazyShaQiuShi
    原文地址: https://blog.csdn.net/qq_25158359/article/details/78846347
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞