您的位置:首页 > 理论基础 > 计算机网络

HttpURL

2016-03-04 21:10 585 查看
* 步骤:

1. new一个URL对象

2. new一个HttpURLConnection对象

3. connection连接

4. getResponseCode()

5. 读取流

// 将网址封装为URL对象
URL url = new URL(path);
// 用url里面的openConnection方法打开连接。
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
// 设置HttpURLConnection一些属性。
// 1:设置请求方式。--默认为 get
connection.setRequestMethod("GET");
// 2:设置连接时间。--可写不可写
connection.setConnectTimeout(5000);
// 3:设置可读。---可写可不写。默认为true
connection.setDoInput(true);
// 4:设置可以往服务器端写入数据------可写可不写。默认为false
connection.setDoOutput(true);
// 连接
connection.connect();
// 服务器端接收到客户端的请求,并返回响应码。
int code = connection.getResponseCode();
if (code == 200) {
// 读取服务器端发送过来的数据。
InputStream is = connection.getInputStream();
FileOutputStream fos = new FileOutputStream("f:\\logo2.jpeg");
byte[] b = new byte[1024];
int length = -1;
while ((length = is.read(b)) != -1) {
fos.write(b, 0, length);
}
is.close();
fos.close();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: