openConnection(proxy) สร้างการเชื่อมต่อพร้อมเส้นทาง กำหนดวิธี HTTP และเนื้อความบน HttpURLConnection ที่คืนมาก่อนเริ่มคำขอ:

Proxy route = new Proxy(Proxy.Type.HTTP,
    new InetSocketAddress("proxy.example", 8080));
HttpURLConnection connection = (HttpURLConnection)
    URI.create("http://www.example.com/submit").toURL().openConnection(route);

try {
    connection.setConnectTimeout(5000);
    connection.setReadTimeout(15000);
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setRequestProperty("Content-Type",
        "application/x-www-form-urlencoded; charset=UTF-8");

    byte[] form = "message=hello+proxy".getBytes(StandardCharsets.UTF_8);
    try (OutputStream out = connection.getOutputStream()) {
        out.write(form);
    }

    int status = connection.getResponseCode();
    System.out.println(status);
    InputStream response = status >= 400
        ? connection.getErrorStream() : connection.getInputStream();
    if (response != null) response.close();
} finally {
    connection.disconnect();
}

ตัวอย่างส่งฟอร์มเล็ก ๆ พิมพ์สถานะ และปิดสตรีมตอบกลับที่ไม่ได้ใช้ แทนขั้นตอนสุดท้ายนั้นด้วยการจัดการเนื้อความตอบกลับของแอปพลิเคชันเมื่อจำเป็นต้องใช้เนื้อความ

ชื่อโฮสต์และพอร์ตของพร็อกซีเป็นของ route สำหรับการทดสอบฟอร์มสาธารณะที่ได้รับอนุญาตโดยไม่มีบัญชีพร็อกซี ให้เลือกที่อยู่ HTTP จากรายการใน รายการพร็อกซี HTTP URL ยังคงเป็นปลายทางของฟอร์ม สำหรับค่าฟอร์มแบบไดนามิก ให้ใช้ URLEncoder เข้ารหัสแต่ละค่าแทนการต่ออินพุตที่ไม่ได้ escape ด้วยเครื่องหมายเท่ากับและแอมเพอร์แซนด์

สตรีมเอาต์พุตส่งไบต์ที่เตรียมไว้ อ่านสถานะหลังจากเขียนและปิด แล้วเลือกสตรีมตอบกลับปกติหรือสตรีมข้อผิดพลาดตามความเหมาะสม การตอบกลับ HTTP ที่ไม่สำเร็จอาจมีเนื้อหาข้อผิดพลาดที่เป็นประโยชน์จากแอปพลิเคชันหรือพร็อกซี

บทความที่เกี่ยวข้อง