HttpURL

* 步骤:
    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();
}

 

posted @ 2016-03-04 21:10  嘉禾世兴  阅读(391)  评论(0编辑  收藏  举报