URL的应用:
获得网页源代码可以用字节流、字符流,流的获取可以用url.openStream(),也可以用con.getInputStream():
字节流:
URL url = new URL("https://www.baidu.com/");
InputStream urlStream = url.openStream();
byte[] b = new byte[1024];
int size = urlStream.read(b, 0, b.length); FileOutputStream fileStream = new FileOutputStream("F:/shutao.html");
while(size > 0)
{
fileStream.write(b, 0, size);
size = urlStream.read(b, 0, b.length);
} fileStream.close();
urlStream.close();
用URLConnection对象来获得流:
URL url = new URL("https://www.baidu.com/");
URLConnection con = url.openConnection();
InputStream conStream = con.getInputStream();
Socket应用:
Socket是使用TCP连接,所以一定要建立与服务器的连接之后,才可以进行读写操作等通信行为。
举例——在Server线程中写,Client线程中读(先从服务器获得Socket,然后就可以在另一端创建对应的Socket建立与服务器的连接;如果双方只是各自创建Socket,就不能形成正确的连接,直接抛出异常):
public class Server extends Thread { @Override
public void run() {
try {
ServerSocket server = new ServerSocket(, );
//通过Socket来获得InputStream、OutputStream
Socket connection = server.accept();
ObjectOutputStream output = new ObjectOutputStream(connection.getOutputStream());
output.write();
output.close();
connection.close();
server.close();
} catch (Exception e) {
e.printStackTrace();
}
} }
public class Client extends Thread { @Override
public void run() {
try {
Socket client = new Socket("127.0.0.1", );
ObjectInputStream input = new ObjectInputStream(client.getInputStream());
System.out.println(input.read());
input.close();
client.close();
} catch (Exception e) {
e.printStackTrace();
}
} }
UDP(用户数据报协议)的应用:
//UDP没有服务器和客户端,只有发送者与接收者
public class Server extends Thread { @Override
public void run() {
try {
//整个过程只需要,指明接收和发送两个端口:
//1、两个端口相同,才能保证正确的通信
//2、发送者在创建数据包时(packet),指定端口;接收者在建立通讯时(socket),指定端口(不这样,会报错的)
//————发送无需建立连接,故创建通讯不指明端口;发送只需将端口写入Packet中,协议决定Packet的传输;而接收则在对应位置准备收信并保存,所以Socket指明端口就行了
DatagramSocket client = new DatagramSocket();
byte[] b = "hello".getBytes();
DatagramPacket data = new DatagramPacket(b, b.length, InetAddress.getByName("127.0.01"), 2121); //发送端口
client.send(data);
client.close();
} catch (Exception e) {
e.printStackTrace();
}
} }
public class Client extends Thread { @Override
public void run() {
try {
DatagramSocket client = new DatagramSocket(2121); //接收端口
byte[] b = new byte[1024];
DatagramPacket data = new DatagramPacket(b, b.length);
client.receive(data); //接收方法会阻塞该线程
System.out.println(new String(b));
System.out.println(new String(data.getData()));
client.close();
} catch (Exception e) {
e.printStackTrace();
}
} }
Cookie的使用:
//Server
<body>
<%
Cookie cookie = new Cookie("username", "shutao"); //Cookie名称+值
cookie.setComment("从这个Cookie中,可获得登录信息(用户名)");
//Cookie默认处于会话级,仅存于浏览器内存中,关闭浏览器后,Cookie被删除
//也可以将Cookie存储在本地,需要设置存储时长
cookie.setMaxAge(60 * 60 * 24); //秒级单位——1天
//刚创建的Cookie在服务器,必须用response对象发送到客户端才能起作用
response.addCookie(cookie);
%>
<jsp:forward page="Client.jsp"></jsp:forward>
</body> //Client
<body>
<%
Cookie[] cookies = request.getCookies();
for(Cookie cookie : cookies)
{
if(cookie.getName().equals("username"))
{
out.println(cookie.getValue());
}
}
%>
</body>
Cookie是保存在客户端的,Session保存在服务器端 ;Cookie最终存放的所有东西都将是String,而Session可以存放Object。
Java解析xml、json数据:
读xml:
public static void main(String[] args) throws Exception
{
Document document = getXmlDocument("test.xml");
Node root = document.getFirstChild();
NodeList nodeList = root.getChildNodes();
for(int i = 0; i < nodeList.getLength(); i++)
{
if(nodeList.item(i) instanceof Element)
{
NodeList list = nodeList.item(i).getChildNodes();
for(int j = 0; j < list.getLength(); j++)
{
Node node = list.item(j);
//这一步是为了:把那个text的什么东西去掉:所以有几次换行缩进,就弄几次NodeList的循环(为了提高效率,应该把所有换行缩进的地方都去掉)
if(node instanceof Element)
System.out.println(node.getTextContent());
}
}
}
} public static Document getXmlDocument(String fileName) throws Exception
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
//import org.w3c.dom.*;
Document document = builder.parse(new File(fileName)); //也可以用流builder.parse(new FileInputStream(fileName));
return document;
}
字符编码转换:
//用户输入到tomcat层时,tomcat会将输入进行编码,默认编码配置为iso-8859-1
//对于中文的字符编码,有4种处理:推荐第2种,更推荐第4种
String utf = new String(str.getBytes("iso-8859-1"), "utf-8"); //1、在获得请求之后,对数据转码
request.setCharacterEncoding("UTF-8"); //2、在获得请求之前,先设置所有请求的编码
//3、直接修改tomcat的配置:设置Connector的URIEncoding="UTF-8"
//4、在过滤器中设置