Java的URL通信

 URL(UniformResourceLocater)是统一资源定位器的简称,URL的值表示网络上的资源,只要按URL规则定义某个资源,那就可以通过其他程序就可以通过URL访问。

package com.dome;
import java.io.*;
import java.net.*;
public class Main {
    public static void main(String[] args) throws IOException {
        URL url=new URL("https://blog.csdn.net/qq_57335683/article/details/134750327");
        System.out.println("Authority ="+url.getAuthority());
        System.out.println("Default port="+url.getDefaultPort()); //返回URL对象的协议使用的默认端口
        System.out.println("File="+url.getFile());
        System.out.println("Host="+url.getHost());
        System.out.println("path="+url.getPath());
        System.out.println("port="+url.getProtocol()); //返回协议名
        System.out.println("Query="+url.getQuery());
        System.out.println("Ref="+url.getRef());
        System.out.println("User Info="+url.getUserInfo()); //返回用户信息部分
        //通过字节流获取网页内容
        InputStreamReader isr =new InputStreamReader(url.openStream());
        BufferedReader bufferedReader=new BufferedReader(isr);
        String s;
        while ((s=bufferedReader.readLine())!=null)
            System.out.println(s);
            bufferedReader.close();
    }

}
class ComWithCgi{
    public static void main(String[] args) throws Exception{ //使用URLConnection实现双向通讯
        URL url=new URL("https://www.baidu.com/");
        //URLClassLoader classLoader=url.openConnection();
        URLConnection connection=url.openConnection();
        connection.setDoOutput(true);
        PrintStream ps=new PrintStream(connection.getOutputStream());
        ps.println("0123456789");
        ps.close();
        DataInputStream dis=new DataInputStream(connection.getInputStream());
        String inputLine;
        while ((inputLine=dis.readLine())!=null){
            System.out.println(inputLine);
        }
        dis.close();
    }
}

你可能感兴趣的:(java,android,开发语言)