Java HTTP GET

HTTP GET

有两种流行的方式使用HTTP GET在Java中:apache第三方库和Java URL

  • Java URL
public static void main(String[] args) {
        try {
            URL url=new URL("http://www.baidu.com");
            URLConnection urlConnection=url.openConnection();
            urlConnection.connect();
             //URL连接之后可以获取输入流
            InputStream inputStream=urlConnection.getInputStream();

            Channel channel= Channels.newChannel(inputStream);
            Channel console=Channels.newChannel(System.out);
           //以下使用NIO流进行数据传送
            ByteBuffer byteBuffer=ByteBuffer.allocateDirect(64);

            int byteread=((ReadableByteChannel) channel).read(byteBuffer);
            while (byteread!=-1){
                byteBuffer.flip();
                ((WritableByteChannel) console).write(byteBuffer);
                byteBuffer.clear();
                byteread=((ReadableByteChannel) channel).read(byteBuffer);
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

上述方法,可以将获取的网页内容打印到控制台(console)。

  • Apache
    引入Maven依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.oneslide.www</groupId>
    <artifactId>httpclient</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>


    <dependencies>

        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/fluent-hc -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>fluent-hc</artifactId>
            <version>4.5.7</version>
        </dependency>

    </dependencies>

</project>

使用fluent API进行GET请求

public static void apache() {
        //more fluent API
        try {
            Content content=Request.Get("http://www.baidu.com")
                    .execute().returnContent();

            InputStream inputStream=content.asStream();
            Files.copy(inputStream, Paths.get("C:\\Users\\94336\\Desktop\\workbunch\\httpclient").resolve("hell.html"), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

上面的代码将文件输出到文件系统的指定路径下

Reference List