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依赖

<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.0modelVersion>

    <groupId>com.oneslide.wwwgroupId>
    <artifactId>httpclientartifactId>
    <version>1.0-SNAPSHOTversion>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-compiler-pluginartifactId>
                <configuration>
                    <source>8source>
                    <target>8target>
                configuration>
            plugin>
        plugins>
    build>


    <dependencies>

        
        <dependency>
            <groupId>org.apache.httpcomponentsgroupId>
            <artifactId>fluent-hcartifactId>
            <version>4.5.7version>
        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

  • Javadoc
  • Oracle tutorial

你可能感兴趣的:(Java)