emptygif
ภาษา: ไทย

ภาษาและเฟรมเวิร์กทั้งหมด

Java standard library (com.sun.net.httpserver) Java

ตัวอย่างโค้ด Java สำหรับ Java standard library (com.sun.net.httpserver) ที่ตอบคำขอไปยัง /pixel.gif ด้วย GIF ว่าง ซึ่งถอดรหัสเพียงครั้งเดียวตอนเริ่มทำงาน

Java standard library (com.sun.net.httpserver) Java

ไฟล์
Pixel.java
รัน
java Pixel.java
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.util.Base64;

public class Pixel {

    private static final byte[] GIF = Base64.getDecoder().decode("R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==");

    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
        server.createContext("/pixel.gif", exchange -> {
            // Contexts match by prefix, so check for the exact path.
            if (!exchange.getRequestURI().getPath().equals("/pixel.gif")) {
                exchange.sendResponseHeaders(404, -1);
                exchange.close();
                return;
            }
            exchange.getResponseHeaders().set("Content-Type", "image/gif");
            exchange.getResponseHeaders().set("Cache-Control", "no-store");
            exchange.sendResponseHeaders(200, GIF.length);
            try (var body = exchange.getResponseBody()) {
                body.write(GIF);
            }
        });
        server.start();
    }
}

เรารันตัวอย่างโค้ดนี้และเทียบไบต์ที่ได้กลับมาแล้ว

ตรวจสอบ

curl -sI http://localhost:8080/pixel.gif

เว็บไซต์ทางการ: Java standard library (com.sun.net.httpserver)

เพิ่มเติมใน Java