首页 > 学院 > 开发设计 > 正文

URL类和HttpUrlConnection

2019-11-06 07:26:33
字体:
来源:转载
供稿:网友

URL类

统一资源定位符(Uniform Resource Locator)是对可以从互联网上 得到的资源的位置和访问方法的一种简洁的表示,是互联网上标准资 源的地址。互联网上的每个文件都有一个唯一的URL,它包含的信息 指出文件的位置以及浏览器应该怎么处理它(网上某个资源的地址)

常用方法

URL url = new URL(“http://www.baidu.com/…”);注意要有协议名,否则报异常

getFile():/abc/aaa.jsp?utm_source=d_hao360…从域名后面的路径开始,含查询的部分getPath():/deal/12612464.html,不含查询的部分,从域名后面的路径开始getPort():返回此URL的port,如果没有设置,则返回-1getHost():获取主机名,例如bj.meituan.comgetPRotocol():返回协议名,httpgetQuery():url?后面的内容URLConnection openConnection() :打开连接import java.io.*;import java.net.URL;public class TestURL { public static void main(String[] args) { String strUrl = "http://www.baidu.com"; BufferedReader br = null; try { URL url = new URL(strUrl); URLConnection uc = url.openConnection(); //uc.connect(); //getInputStream会隐含的进行connect br = new BufferedReader(new InputStreamReader(uc.getInputStream(),"UTF-8")); String str = ""; while((str = br.readLine()) != null){ System.out.println(str); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ if(null != br){ try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } }}InputStream openStream():打开输入流

HttpURLConnection

disconnect() 断开连接getResponseCode() 返回服务器的响应码 404 200setRequestMethod(String method) 设置 URL 请求的方法setConnectTimeout(int timeout) 设置连接超时时间setDoInput(boolean doinput) 设置允许向服务写数据getOutputStream()向服务器写流getInputStream()得到服务器返回的数据流
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表