簡體   English   中英

如何提交帶有意圖語法錯誤的 HTTP 請求?

[英]How to submit HTTP request with an INTENTIONAL syntax error?

我正在嘗試編寫一個簡單的測試,我向http://localhost:12345/%提交請求,知道這是一個非法的 URI,因為我想斷言我的 HTTP 服務器的錯誤處理代碼行為正確。 但是,我很難強迫 Java 這樣做。

如果我嘗試使用URI.create("localhost:12345/%")創建 Java 11 HttpRequest ,我會得到一個 URISyntaxException,這是正確的,但沒有幫助。

同樣,使用 ws-rs WebTarget

ClientBuilder.newBuilder().build().target("http://localhost:12345").path("/%")

為我構建了一個指向/%25的 WebTarget ,這通常會很有幫助,但在這種特殊情況下並不是我想要的。

有沒有一種方法可以測試我的錯誤處理行為而不訴諸低級字節流操作?

另一種可能性是使用普通 Socket - 如果您知道協議(尤其是使用新的文本塊功能),這很容易。 這將允許您以任何您喜歡的方式錯誤格式化請求。 閱讀響應並分析結果 - 當然 - 涉及更多:

String request = """
               GET %s HTTP/1.1\r
               Host: localhost:%s\r
               Connection: close\r
               \r
               """.formatted("/%", port);
try (Socket client = new Socket("localhost", port);
     OutputStream os = client.getOutputStream();
     InputStream in = client.getInputStream()) {

    os.write(request.getBytes(StandardCharsets.US_ASCII));
    os.flush();

    // This is optimistic: the server should close the
    // connection since we asked for it, and we're hoping
    // that the response will be in ASCII for the headers
    // and UTF-8 for the body - and that it won't use
    // chunk encoding.
    byte[] bytes = in.readAllBytes();
    String response = new String(bytes, StandardCharsets.UTF_8);
    System.out.println("response: " + response);

 }

諾亞的評論使我走上了正確的道路; 我能夠用URL class 做到這一點:

@Test
public void testUriMalformed() throws Exception {
    final URL url = new URL(TEST_URI + "/%");
    final HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    
    final int code = connection.getResponseCode();
    final String contentType = connection.getHeaderField("Content-Type");
    final String entity = IOUtils.toString(connection.getErrorStream(), Charsets.UTF_8);
    
    assertEquals(500, code);
    assertEquals(MediaType.APPLICATION_JSON, contentType);
    assertTrue(entity.contains("error_id"));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM