Java Tutorial/Network/HTTP Server
Содержание
Grabbing a page using socket
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.URL;
public class Main {
public static void main(String[] args) throws Exception {
String pageAddr = "http://www.google.ru/index.htm";
URL url = new URL(pageAddr);
String websiteAddress = url.getHost();
String file = url.getFile();
Socket clientSocket = new Socket(websiteAddress, 80);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket
.getInputStream()));
OutputStreamWriter outWriter = new OutputStreamWriter(clientSocket.getOutputStream());
outWriter.write("GET " + file + " HTTP/1.0\r\n\n");
outWriter.flush();
BufferedWriter out = new BufferedWriter(new FileWriter(file));
boolean more = true;
String input;
while (more) {
input = inFromServer.readLine();
if (input == null)
more = false;
else {
out.write(input);
}
}
out.close();
clientSocket.close();
}
}
Lightweight HTTP Server
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class HttpServerDemo {
public static void main(String[] args) throws IOException {
InetSocketAddress addr = new InetSocketAddress(8080);
HttpServer server = HttpServer.create(addr, 0);
server.createContext("/", new MyHandler());
server.setExecutor(Executors.newCachedThreadPool());
server.start();
System.out.println("Server is listening on port 8080" );
}
}
class MyHandler implements HttpHandler {
public void handle(HttpExchange exchange) throws IOException {
String requestMethod = exchange.getRequestMethod();
if (requestMethod.equalsIgnoreCase("GET")) {
Headers responseHeaders = exchange.getResponseHeaders();
responseHeaders.set("Content-Type", "text/plain");
exchange.sendResponseHeaders(200, 0);
OutputStream responseBody = exchange.getResponseBody();
Headers requestHeaders = exchange.getRequestHeaders();
Set<String> keySet = requestHeaders.keySet();
Iterator<String> iter = keySet.iterator();
while (iter.hasNext()) {
String key = iter.next();
List values = requestHeaders.get(key);
String s = key + " = " + values.toString() + "\n";
responseBody.write(s.getBytes());
}
responseBody.close();
}
}
}
POSTing data to an HTTP server
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.URL;
import java.net.URLConnection;
public class Main {
public static void main(String[] args) throws Exception {
URL url = new URL("http://localhost:8080/postedresults.jsp");
URLConnection conn = url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
String content = "CONTENT=HELLO JSP !&ONEMORECONTENT =HELLO POST !";
out.writeBytes(content);
out.flush();
out.close();
DataInputStream in = new DataInputStream(conn.getInputStream());
String str;
while (null != ((str = in.readUTF()))) {
System.out.println(str );
}
in.close();
}
}
Sending a POST Request Using a Socket
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URLEncoder;
public class Main {
public static void main(String[] argv) throws Exception {
String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
Socket socket = new Socket("127.0.0.1", 8080);
String path = "/servlet";
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
wr.write("POST " + path + " HTTP/1.0\r\n");
wr.write("Content-Length: " + data.length() + "\r\n");
wr.write("Content-Type: application/x-www-form-urlencoded\r\n");
wr.write("\r\n");
wr.write(data);
wr.flush();
BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
wr.close();
rd.close();
}
}
Web ping
import java.net.InetAddress;
import java.net.Socket;
public class Main {
public static void main(String[] args) throws Exception {
InetAddress addr;
Socket sock = new Socket(args[0], 80);
addr = sock.getInetAddress();
System.out.println("Connected to " + addr);
sock.close();
}
}