啥也不說了,直接上代碼,簡單的示例。html
服務端代碼:java
package dyan.server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.InetSocketAddress; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; import com.sun.net.httpserver.spi.HttpServerProvider; public class DealMain { public static void main(String[] args) throws Exception { HttpServerProvider provider = HttpServerProvider.provider(); HttpServer server = provider.createHttpServer(new InetSocketAddress(6688), 10); server.createContext("/dyan", new DealMain().new DyanHttpHandler()); server.setExecutor(null); server.start(); } class DyanHttpHandler implements HttpHandler { @Override public void handle(HttpExchange arg0) throws IOException { System.out.println("accept an exchange from internet....."); String resp = "your request message i get it!"; BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(arg0.getRequestBody())); System.out.println(bufferedReader.readLine()); arg0.sendResponseHeaders(200, resp.getBytes().length); OutputStream out = arg0.getResponseBody(); out.write(resp.getBytes()); out.flush(); arg0.close(); } } }
請求代碼:ide
public static void main(String[] args) throws Exception { URL url = null; HttpURLConnection urlConnection = null; url = new URL("http://localhost:6688/dyan"); urlConnection = (HttpURLConnection)url.openConnection(); urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setUseCaches(false); System.out.println("begin send parameters...."); urlConnection.getOutputStream().write("i am dyan".getBytes()); urlConnection.getOutputStream().flush(); urlConnection.getOutputStream().close(); InputStream in = urlConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in)); System.out.println(bufferedReader.readLine()); bufferedReader.close(); urlConnection.disconnect(); }
先執行服務端代碼,將服務端啓動起來,來接收請求。url
再執行請求代碼,發起請求。spa
控制檯打印信息以下:.net
一、請求端code
begin send parameters....
your request message i get it!server
二、服務端htm
accept an exchange from internet.....
i am dyanblog