在 Java 中,“HTTP 超文本传输”通常指的是通过 HTTP 协议发送和接收 HTML(超文本)。下面从概念 → 常见方式 → 示例逐步说明。
示例:
GET /index.html HTTP/1.1
Host: example.com
服务器返回:
HTTP/1.1 200 OK
Content-Type: text/html
<html><body>Hello</body></html>
import com.sun.net.httpserver.*;
import java.io.*;
import java.net.*;
public class HtmlServer {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/", exchange -> {
String html = "<html><body><h1>Hello HTTP</h1></body></html>";
byte[] bytes = html.getBytes();
exchange.getResponseHeaders().add("Content-Type", "text/html; charset=utf-8");
exchange.sendResponseHeaders(200, bytes.length);
OutputStream os = exchange.getResponseBody();
os.write(bytes);
os.close();
});
server.start();
}
}
浏览器访问:
http://localhost:8080
import java.net.http.*;
import java.net.URI;
public class HtmlClient {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://example.com"))
.build();
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body()); // HTML 超文本
}
}
@RestController
public class HtmlController {
@GetMapping("/page")
public String page() {
return "<html><body><h1>Spring HTML</h1></body></html>";
}
}
或返回页面(HTML 文件):
@Controller
public class PageController {
@GetMapping("/index")
public String index() {
return "index"; // templates/index.html
}
}
✅ HTTP 只是“通道”
✅ 超文本 = HTML 文本
✅ Java 可以:
如果你是指:
可以告诉我,我可以给你更针对性的示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。