您的位置:首页 > 理论基础 > 计算机网络

JAVA基础之网络编程

2015-11-27 00:00 525 查看
Socket socket = new Socket();
try {
socket.connect(new InetSocketAddress("*.com", 80), 10000);
InputStream inputStream = socket.getInputStream();
Scanner in = new Scanner(inputStream);
while (in.hasNextLine()) {
String line = (String) in.next();
System.out.println(line);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

//连接超时时new Socket会一直阻塞,直到连通
Socket socket = new Socket("*.com", 80);

InetAddress[] address = InetAddress.getAllByName("*.com");
for (InetAddress a : address) {
System.out.println(a);
}
//localhost地址
InetAddress local = InetAddress.getLocalHost();
System.out.println(local);

ServerSocket server = new ServerSocket(8189);
//监控8189端口
Socket comeSocket = server.accept();
InputStream in = comeSocket.getInputStream();
Scanner scanner = new Scanner(in);
OutputStream out = comeSocket.getOutputStream();
PrintWriter writer = new PrintWriter(out, true);
while (scanner.hasNext()) {
String string = (String) scanner.next();
System.out.println(string);
writer.println("test 8189=" + string);
}
comeSocket.close();

ServerSocket server = new ServerSocket(8189);
//监控8189端口
while (true) {
int i = 0;
Socket comeSocket = server.accept();
Runnable r = new ThreadedEchoHandler(comeSocket);
Thread t = new Thread(r);
t.start();
i++;
}

//ThreadedEchoHandler.java
public class ThreadedEchoHandler implements Runnable {
private Socket imcoming;

public ThreadedEchoHandler(Socket imcoming) {
this.imcoming = imcoming;
}

@Override
public void run() {
try {
InputStream inputStream = imcoming.getInputStream();
Scanner scanner = new Scanner(inputStream);
OutputStream out = imcoming.getOutputStream();
PrintWriter writer = new PrintWriter(out, true);
while (scanner.hasNext()) {
String string = (String) scanner.next();
System.out.println(string);
writer.println("test 8189=" + string);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
imcoming.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

//Socket半关闭,比如http请求(一次性)时适用
Socket socket = new Socket();
try {
socket.connect(new InetSocketAddress("*.com", 80), 10000);
InputStream inputStream = socket.getInputStream();
Scanner in = new Scanner(inputStream);
PrintWriter writer = new PrintWriter(socket.getOutputStream());
//send request data
writer.print("test");
writer.flush();
socket.shutdownOutput();//socket半关闭状态(输出关闭,输入不关闭)
while (!Thread.currentThread().isInterrupted()) {
while (in.hasNextLine()) {
String string = (String) in.next();
}
}
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

SocketChannel channel = SocketChannel.open(new InetSocketAddress("", 80));
Scanner in = new Scanner(channel);
OutputStream outputStream = Channels.newOutputStream(channel);

获取web数据

1)URL(Uniform Resource Locator)统一资源定位符 是 URI(Uniform Resource Identifier)的一个特例

mailto:cay@horstmann.com

不属于URL,因为无法定位任何数据,像这样的URI称之为URN(Uniform Resource name)统一资源名称。

2)获取web表单数据

URL url = new URL("");
InputStream inputStream = url.openStream();
Scanner in = new Scanner(inputStream);

String urlName;
if (args.length > 0)
urlName = args[0];
else
urlName = "http://news.163.com";

URL url = new URL(urlName);
URLConnection connection = url.openConnection();
connection.connect();
//header fields
Map<String, List<String>> headers = connection.getHeaderFields();
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
String key = entry.getKey();
for (String value : entry.getValue())
System.out.println(key + ":" + value);
}

//print header elements
System.out.println("------------------------------------------");
System.out.println("getContentType:" + connection.getContentType());
System.out.println("getContentLength:" + connection.getContentLength());
System.out.println("getContentEncoding:" + connection.getContentEncoding());
System.out.println("getDate:" + connection.getDate());
System.out.println("getExpiration:" + connection.getExpiration());
System.out.println("getLastModified:" + connection.getLastModified());
System.out.println("------------------------------------------");

Scanner in = new Scanner(connection.getInputStream());
//print first ten lines
for (int n = 1; in.hasNextLine() && n <= 10; n++) {
System.out.println(in.nextLine());
if (in.hasNextLine()) System.out.println("...");
}

3)提交web表单数据

保留字符:A-Z、a-z、0-9、. -*_

+代替所有空格

将其它所有字符编码为UTF-8,并将每个字节都编码为%后面紧跟1,2位16进制

比如:New York, NY可以使用New+York%2C+NY

public static void main(String[] args) {
Properties props = new Properties();
try {
InputStream in = new FileInputStream("");
props.load(in);
String url = props.remove("url").toString();
String result = doPost(url, props);
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}

public static String doPost(String urlSting, Map<Object, Object> map) throws Exception {
URL url = new URL(urlSting);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());
boolean first = true;
for (Map.Entry<Object, Object> pair : map.entrySet()) {
if (first)
first = false;
else
out.print('&');
String name = pair.getKey().toString();
String value = pair.getValue().toString();
out.print(name);
out.print("=");
out.print(URLEncoder.encode(value, "UTF-8"));
}

StringBuilder response = new StringBuilder();
try {
Scanner in = new Scanner(connection.getInputStream());
while (in.hasNextLine()) {
response.append(in.nextLine());
response.append("\n");
}
} catch (Exception e) {
if (!(connection instanceof HttpURLConnection))
throw e;
InputStream err = ((HttpURLConnection) connection).getErrorStream();
if (err == null)
throw e;
Scanner in = new Scanner(err);
response.append(in.nextLine());
response.append("\n");
}
return response.toString();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: