Java 如何提交带有故意语法错误的HTTP请求?
我正在尝试编写一个简单的测试,向Java 如何提交带有故意语法错误的HTTP请求?,java,java-http-client,Java,Java Http Client,我正在尝试编写一个简单的测试,向http://localhost:12345/%,知道这是一个非法的URI,因为我想断言我的HTTP服务器的错误处理代码行为正确。然而,我很难强迫Java这么做 如果我尝试使用URI.create(“localhost:12345/%”)创建一个Java11HttpRequest,我会得到一个URISyntaxException,它是正确的,没有帮助 类似地,使用ws-rsWebTarget: ClientBuilder.newBuilder().build().
http://localhost:12345/%
,知道这是一个非法的URI,因为我想断言我的HTTP服务器的错误处理代码行为正确。然而,我很难强迫Java这么做
如果我尝试使用URI.create(“localhost:12345/%”)创建一个Java11HttpRequest
,我会得到一个URISyntaxException,它是正确的,没有帮助
类似地,使用ws-rsWebTarget
:
ClientBuilder.newBuilder().build().target("http://localhost:12345").path("/%")
为我构建一个指向/%25
的WebTarget,这通常会非常有用,但在这种特殊情况下,这不是我想要的
有没有一种方法可以测试我的错误处理行为而不必求助于低级ByTestStream操作?Noah的评论引导我走上了正确的道路;我可以通过URL
类实现这一点:
@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"));
}
另一种可能是只使用普通套接字——如果您了解协议(特别是使用新的文本块功能),那么就很容易了。这将允许您以任何喜欢的方式错误格式化请求。当然,阅读响应和分析结果更为复杂:
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);
}
仔细阅读API,我想知道您是否可以使用自定义StreamHandler
构建一个不兼容的API。如果是这样的话,那么希望您可以通过HttpURLConnection
发送它。这对我来说是一个测试平台的过程。您不必测试apachehttpd或Tomcat或您的HTTP服务器。您必须测试您的应用程序。@user207421我负责此平台的正确配置和错误处理行为。谢谢你的关心。哦,哈,你甚至不需要那个特殊的构造器!