本示例演示如何在Java中利用com.sun.net.httpserver包进行HTTP请求的发送和处理,包括创建服务器、设置处理器及响应客户端等操作。适合初学者学习网络编程基础。
在Java编程环境中,HTTP通信是常见且至关重要的任务,它涉及到客户端与服务器之间的数据交换。实现这一功能可以使用多种库,在这里我们关注`com.sun.net.httpserver`包,这是一个内置的轻量级HTTP服务器解决方案,适合用于测试、原型设计以及简单的应用开发。
以下是一个启动HTTP服务器的例子:
```java
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpHandler;
public class ERPHttpServer {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext(/hello, new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
String response = Hello, World!;
t.getResponseHeaders().add(Content-Type, text/plain);
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
```
在这个例子中,我们创建了一个监听8000端口的服务器,并设置了一个处理器`MyHandler`。当收到针对路径“/hello”的请求时,服务器将返回字符串Hello, World!。
接下来是使用Java的标准库发送HTTP GET请求的例子:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HTTPClient {
public static void main(String[] args) throws Exception {
URL url = new URL(http://localhost:8000/hello);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(GET);
connection.setRequestProperty(Accept, application/json);
if (connection.getResponseCode() != 200) {
throw new RuntimeException(Failed : HTTP error code : + connection.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
connection.disconnect();
}
}
```
这个客户端程序向服务器端的“/hello”路径发送一个GET请求,并打印出响应的内容。
尽管`com.sun.net.httpserver`包的功能相对简单,但它足够处理许多基本HTTP交互需求。然而,在需要支持HTTPS、管理cookies或处理WebSocket等更复杂的应用场景时,可能需要考虑使用第三方库如Apache HttpClient或OkHttp来实现这些功能。