问题
- Socket
- ServerSocket
- InetAddress
- 多线程ServerSocket
- URL/URLConnection
- URI
- Email
解答
- InetAddress
获取本机ip,根据主机名获取ip
public class WebTest{
@Test public void testFtp() throws IOException {
Socket socket = new Socket("10.202.62.9",21);
InputStream inputStream = socket.getInputStream();
Scanner scanner = new Scanner(inputStream);
while (scanner.hasNextLine()){
String line = scanner.nextLine();
if (" ".equals(line)){
break;
}
System.out.println(line);
}
inputStream.close();
}
@Test
public void testInetAddress() throws UnknownHostException {
//获取本机地址
InetAddress localHost = InetAddress.getLocalHost();
System.out.println("主机名:"+localHost.getHostName());
System.out.println("ip地址: "+localHost.getHostAddress());
//根据hostname获取地址
InetAddress byName = InetAddress.getByName("daiyutagedeMacBook-Pro.local");
System.out.println(byName.getHostAddress());
System.out.println(new String(byName.getAddress()));
}
@Test
public void testSocketServer(){
try(ServerSocket s = new ServerSocket(8189)) {
try(Socket socket = s.accept()){
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
try(Scanner scanner = new Scanner(in)){
PrintWriter pw = new PrintWriter(out,true);
pw.println("Hello Entey Bye to Exit");
boolean done = false;
while(!done && scanner.hasNextLine()){
String line = scanner.nextLine();
pw.println(line);
System.out.println(line);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testURL() throws IOException {
URL url = new URL("http://www.baidu.com");
InputStream inputStream = url.openStream();;
Scanner scanner = new Scanner(inputStream);
while(scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
}
@Test public void testURLConnection() throws IOException {
URL url = new URL("http://www.qq.com");
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
Map<String, List<String>> headerFields = urlConnection.getHeaderFields();
Set<String> strings = headerFields.keySet();
for (String string : strings) {
System.out.println(string+" "+headerFields.get(string));
}
System.out.println(urlConnection.getContentEncoding());
}
@Test public void testMail() throws IOException {
Socket socket = new Socket("mail.xxx.com",25);
InputStream inputStream = socket.getInputStream();
Scanner scanner = new Scanner(inputStream);
while (scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println(line);
}
}
}