为什么要说介绍这几个类,是因为我们在工作中会接触到通过客服端调用的方式
1、Inet4Address、Inet6Address、InetAddress
这两个类主要链接远程机器用的,父类是InetAddress,先来看看是怎么实现拿到机器的ip地址的
public InetAddress[] lookupAllHostAddr(String var1) throws UnknownHostException { String[] var2 = new String[]{"A", "AAAA", "CNAME"}; DirContext var3; try { var3 = this.getTemporaryContext(); //获取dns目录树对应的所有和此域名的内容 } catch (NamingException var13) { throw new Error(var13); } .......... }
上面这个方法是在DNSNameService里面的,主要是用来查找域名对应的ip地址(多个)
2、URL、URLConnection、HttpURLConnection
为什么要将上面的InetAddress类,主要是想大家了解完整的一个过程(如下图)
接下来主要讲下URL、URLConnection、HttpURLConnection 首先给出一段代码
URL url = new URL("http://localhost:8080/web/test/write"); //解析url路径,验证url格式(比如协议等等) HttpURLConnection urlConnection = null; StringBuilder stringBuilder = new StringBuilder(); try { urlConnection = (HttpURLConnection) url.openConnection();//创建连接对象(这里有很多协议,我们看 HttpUrlConnection这个) urlConnection.setRequestMethod("POST"); //设置对象的链接属性 urlConnection.setRequestProperty("ContentType","application/json;charset:utf-8"); int code = urlConnection.getResponseCode();//重要,这里是真正的建立和远程服务器的链接(里面保护和发现机器 ip地址等方法,其实就是实现了InetAddress的方法) if(code!=200) return; try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), Charset.forName("utf-8"))); ){ String rep = null; while ((rep = bufferedReader.readLine())!=null){ stringBuilder.append(new String (rep)); } }catch (Exception e){ e.printStackTrace(); } System.out.println(urlConnection.getHeaderFields()); System.out.println(stringBuilder.toString()); }catch (Exception e){ e.printStackTrace(); }finally { if(urlConnection!=null) urlConnection.disconnect(); }