URLConnection: 这是一个抽象类
常用方法:
connect(): 打开此url引用的资源的通信连接。
get|setDoInput(): URLConnection的input字段,默认为true
get|setDoOutput(): 和output字段有关,默认是false
getContentType(): 返回content-type头字段的值
getContentLenth(): 返回content-lengthz头字段的值
getInputStream: 返回从此打开的连接读取的输入流
getOutputStream: 返回从此打开的链接读取的输出流(当doOutput字段为默认时报错)
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.net.URL;
import java.net.URLConnection;
public class URLConnectionDemo01 {
public static void main(String[] args) throws Exception {
String spec = "https://ss3.baidu.com/-fo3dSag_xI4khGko9WTAnF6hhy/super/whfpf%3D425%2C260%2C50/sign=9b4692b62e34349b74533dc5afd721fc/a8773912b31bb0514672c084307adab44bede0cc.jpg";
//确定资源的位置
URL url = new URL(spec);
//打开链接
URLConnection conn = url.openConnection();
//一些方法
System.out.println(conn.getContentLength());
System.out.println(conn.getContentType());
//获得流
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("a2.jpg"));
byte[] b = new byte[1024];
int len = 0;
while ((len = bis.read(b)) != -1) {
bos.write(b, 0, len);
}
//关流
bos.flush();
bos.close();
bis.close();
}
}
下面这代代码设置了向服务器写数据:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
public class URLConnectionDemo02 {
public static void main(String[] args)throws Exception {
String path = "http://127.0.0.1:8080/day028_web/LoginServlet";
String userName = "Mixm";
String passWord = "0906";
String strSend = "userName=" + userName+"&passWord="+ passWord;
URL url = null;
URLConnection conn = null;
BufferedReader br = null;
OutputStream out = null;
try {
//确定资源的位置
url = new URL(path);
//打开链接
conn = url.openConnection();
//设置可以向服务器写入数据
conn.setDoOutput(true);
//得到向服务器写的流
out = conn.getOutputStream();
//向服务器写数据
out.write(strSend.getBytes());
//得到服务器的回送数据
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
System.out.println(br.readLine());
} finally{
//关闭流
if(br != null){
br.close();
}
if(out != null){
out.close();
}
}
}
}