详解GET方法:HttpURLConnection从网络获取资源
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* 客户端程序:用于根据指定的网址。访问网络的数据
// 拿获取百度服务器端的logo图片为例
*
* @author Administrator
*
*/
public class Demo01_HttpURLConnection {
public static void main(String[] args) {
FileOutputStream fos = null;
// step1:先获取网络地址
String baseUrl = “https://www.baidu.com/img/bd\_logo1.png“;
// step2:根据网址,构建URL对象。用于打开和该网址指向的资源,建立连接
try {
URL url = new URL(baseUrl);
// step3:根据url,打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// step4:设置本次网络请求的参数
// 设置请求方式
connection.setRequestMethod(“GET”);// 该方法的参数:所有的参数字母全部大写。
// 设置连接超时
connection.setConnectTimeout(5000);
// step5:开始连接
connection.connect();// 该行代码可以省略
// step6:获取服务端的响应码
int responseCode = connection.getResponseCode();
System.out.println(responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {// 200
// step7:获取流,读数据
InputStream inputStream = connection.getInputStream();
String fileName = baseUrl.substring(baseUrl.lastIndexOf(“/“) + 1);
File file = new File(“D:\\Ruby\\pro”, fileName);
fos = new FileOutputStream(file);
byte[] bs = new byte[1024];
int len = 0;
while ((len = inputStream.read(bs)) != -1) {
fos.write(bs, 0, len);
}
System.out.println(“图片下载完毕。。。”);
}
// connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
GitHub: https://github.com/HuaDanJson
还没有评论,来说两句吧...