文章目录
(主要参考《疯狂Java》)
1. 网络编程基础知识
- 网络基础知识
计算机网络使现代通信技术与计算机技术相结合的产物。通过计算机网络可以向全社会提供各种信息和服务。
计算机网络按照大小和延申范围可以划分为:局域网(LAN)、城域网(MAN)、广域网(WAN)。Internet可以看作世界上最大的广域网。
计算机网络中实现通信必须有一些约定,即通信协议。通信协议负责对传输速率、传输代码、代码结构、传输控制步骤、出错控制等指定处理标准。通信协议通常由三个部分组成:语义部分(决定双方对话的类型)、语法部分(决定双发对话的格式)、变换规则(决定双方的应答关系)。
ISO于1987年提出开放系统互连参考模型(OSI,Open System Interconnection),OSI力求网络简化,以模块化的方式设计网络。他把计算机网络分为物理层、数据链路层、网络层、传输层、会话层、表示层、应用层七层。OSI模式已成为各种计算机网络结构的参考标准。
通信协议中两种种很重要的协议:IP协议,(Internet Protocol,互联网协议),支持网间互联的数据报协议,提供网间连接的完善功能;TCP(Transmission Control Protocol)协议,传输控制协议,规定一种可靠的数据信息传递服务。他们是在同一个时期作为一个协议来设计的,在功能上也是互补的。因此通常把他们统称为TCP/IP协议,它最早出现在UNIX操作系统中,现在几乎所有操作系统都支持,TCP/IP协议是Internet中最常用的基础协议。
- IP地址和端口号
IP地址用来唯一的标识网络中的一个通信实体。IP地址是数字型的,32位的整数,为了便于记忆通常分成4个8位的二进制数。每个8位整数可以转换为一个0~255的十进制整数。NIC(Internet Network Information Center)统一负责全球Internet IP地址的规划、管理,而Inter NIC、APNIC、RIPE三大网络信息中心具体负责美国及其他地区的IP地址分配。亚太地区的IP管理由APNIC来负责。
2. Java的基本网络支持
2.1 InetAddress
Java用InetAddress类来代表IP地址,InetAddress下有两个子类:InetAddress、Inet6Address,分别代表IPv4(Internet Protocal version 4)和IPv6。
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class inetaddress_test {
public static void main(String[] args) throws IOException {
InetAddress ip=InetAddress.getByName("www.baidu.com");
System.out.println(ip.isReachable(2000));
System.out.println(ip.getHostAddress());
InetAddress local=InetAddress.getByAddress(new byte[]{127,0,0,1});
System.out.println(local.isReachable(5000));
System.out.println(local.getCanonicalHostName());
}
}
2.2URLDecoder、URLEncoder
URLDecoder和URLEncoder用于完成普通字符串和application/x-www-form-urlencoded MIME字符串的相互转换。当我们百度搜索的关键词中包含中文时URL地址中对应一串特殊的字符串就是application/x-www-form-urlencoded MIME字符串。我们编程过程中需要两种字符串的相互转换时就需要URLDecoder和URLEncoder。
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
public class urlencoder_test {
public static void main(String[] args) throws UnsupportedEncodingException {
String keyword= URLDecoder.decode("%E4%B8%9C%E9%A3%8E%E8%B0%B7%E6%97%A9%E8%8B%97","utf-8");
//https://www.sogou.com/tx?query=%E4%B8%9C%E9%A3%8E%E8%B0%B7%E6%97%A9%E8%8B%97&_ast=1581570699&_asf=www.sogou.com&w=01029901&pid=sogou-site-1f2b8183cd1e469a&duppid=1&cid=&s_from=result_up&sut=24828&sst0=1581570786865&lkt=3%2C1581570772091%2C1581570772780&sugsuv=001A584578E3E9845E22EAFFAEE25620&sugtime=1581570786865
System.out.println(keyword);
String urlstr= URLEncoder.encode("东风谷早苗","GBK");//utf-8
System.out.println(urlstr);
}}
2.3 URL、URLConnection和URLPermission
URL(Uniform Resource Location)代表统一资源定位器。是可以只想互联网资源的指针。通常,URL由协议名、主机、端口和资源组成,即
protocol://host:port/resourceName
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;
import java.util.List;
import java.util.Map;
public class urltest {
public static void main(String[] args) {
String res="";
try {
var url = new URL("https://baike.sogou.com/v4623310.htm?fromTitle=%E4%B8%9C%E9%A3%8E%E8%B0%B7%E6%97%A9%E8%8B%97");
System.out.println(url.getFile()+"\n"+url.getHost()+"\n"+url.getPath()+
"\n-"+url.getPort()+"\n"+url.getQuery()+"---");
URLConnection conn=url.openConnection();
conn.setRequestProperty("accept","*/*");
conn.setRequestProperty("connection","Keep-Alive");
conn.setRequestProperty("user-agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400");
conn.connect();
Map<String, List<String>> map=conn.getHeaderFields();
for(var key:map.keySet()){
System.out.println(key+"--->"+map.get(key));
}
try(
var in=new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"))
){
String line;
while((line=in.readLine())!=null){
res+="\n"+line;
}
System.out.println(res);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String ress="" ;
URL purl= null;
try {
purl = new URL("http://localhost:8888/abc/login.jsp");
URLConnection conn=purl.openConnection();
conn.setRequestProperty("accept","*/*");
conn.setRequestProperty("connection","Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400");
conn.setDoOutput(true);
conn.setDoInput(true);
try(
var out=new PrintWriter(conn.getOutputStream())
){
out.print("name=crazyit.org&pass=leegang");
out.flush();
}
try(
var in=new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"))
){
String line;
while ((line=in.readLine())!=null){
ress+="\n"+line;
}
System.out.println(ress);
}
conn.connect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上程序向Web站点发送GET请求成功了,但POST请求失败了。
3. 基于TCP的网络编程
ServerSocket创建TCP服务器端
以下建立服务器端
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class server_test {
public static void main(String[] args) throws IOException {
var ss=new ServerSocket(3000);
while(true){
Socket s=ss.accept();
var ps=new PrintStream(s.getOutputStream());
ps.println("The--World!!!");
ps.close();s.close();
}
}
}
使用Socket建立于指定IP地址、指定端口的连接,并使用Socket获取输入流读取数据
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class client_test {
public static void main(String[]args) throws IOException {
var socket=new Socket("127.0.0.1",3000);
var br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line=br.readLine();
System.out.println("get data:"+line);
br.close();socket.close();
}
}
来源:CSDN
作者:xhh22900
链接:https://blog.csdn.net/xhh22900/article/details/104295989