网络编程(URL)

目录

URL:

1.java原生URL类

2.apache HttpClient

 


URL:

 protocol://host:port/path?query#fragment

  • 协议(protocol):可以是 HTTP、HTTPS、FTP 和 File
  • 主机(host:port):www.baidu.com
  • 端口号(port): 80 ,以上URL实例并未指定端口,因为 HTTP 协议默认的端口号为 80。
  • 文件路径(path):/index.html
  • 请求参数(query):language=cn
  • 定位位置(fragment):name,定位到网页中 id 属性为 name的 HTML 元素位置 。

1.java原生URL类

java.net.URL 包中定义了URL类,该类用来处理有关URL的内容

1.创建远程url连接对象

通过给定的参数(协议、主机名、端口号、文件名)创建URL。
public URL(String protocol, String host, int port, String file) throws MalformedURLException.

使用指定的协议、主机名、文件名创建URL,端口使用协议的默认端口。
public URL(String protocol, String host, String file) throws MalformedURLException

通过给定的URL字符串创建URL
public URL(String url) throws MalformedURLException

使用基地址和相对URL创建
public URL(URL context, String url) throws MalformedURLException

2.通过远程url连接对象打开一个连接

打开一个URL连接,返回一个 java.net.URLConnection
public URLConnection openConnection() throws IOException
    //获取http连接,返回HttpURLConnection对象
    //获取JAR文件,返回JarURLConnection对象

URLConnection 方法:


//返回URL的输入流,用于读取资源
public InputStream getInputStream() throws IOException

//返回URL的输出流, 用于写入资源
public OutputStream getOutputStream() throws IOException

//添加请求属性
addRequestProperty("encoding", "UTF-8");
//允许输入
setDoInput(true);
//允许输出
setDoOutput(true);
//请求方式
setRequestMethod("POST");

例:


//获取baidu首页的url连接
URL url = new URL("http://www.baidu.com");
URLConnection urlConn = url.openConnection();

///强转成httpURLConnection类 
HttpURLConnection conn = null;
if(urlConn instanceof HttpURLConnection){
  conn = (HttpURLConnection) urlConn;
}

// 发送请求
conn.connect();

//通过connection连接,获取输出输入流
             //输入
            PrintWriter pw = new PrintWriter(new BufferedOutputStream(connection.getOutputStream()));
            pw.write("code=001&name=测试");
            pw.flush();
            pw.close();
            //输出
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            String line = null;
            StringBuilder result = new StringBuilder();
            while ((line = br.readLine()) != null) { // 读取数据
                result.append(line + "\n");
            }

// 关闭远程连接
connection.disconnect();

2.apache HttpClient

猜你喜欢

转载自blog.csdn.net/xyc1211/article/details/83047984