简体   繁体   中英

How to submit HTTP request with an INTENTIONAL syntax error?

I'm trying to write a simple test where I submit a request to http://localhost:12345/% , knowing that this is an illegal URI, because I want to assert that my HTTP Server's error-handling code behaves correctly. However, I am having a hard time forcing Java to do this.

If I try to create a Java 11 HttpRequest with URI.create("localhost:12345/%") , I get a URISyntaxException, which is correct and not helpful.

Similarly, using a ws-rs WebTarget :

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

builds me a WebTarget pointing to /%25 , which would normally be very helpful, but is not what I want in this particular situation.

Is there a way to test my error-handling behavior without resorting to low-level bytestream manipulation?

Another possibility is just to use plain Socket - it's easy enough if you know the protocol (especially if using the new text-block feature). This will allow you to misformat the request in any way you like. Reading the response and analysing the result is - of course - a bit more involved:

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);

 }

Noah's comment lead me down the right path; I was able to do this with the 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"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM