您发布的代码按预期执行。这是一个完整的测试用例来证明它:
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URL;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
public class Http206Test {
private HttpServer server;
@Before
public void setUp() throws Exception {
server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/", new HttpHandler() {
public void handle(HttpExchange t) throws IOException {
t.sendResponseHeaders(206, 0);
t.getResponseBody().write("I'm a 206 response".getBytes());
t.getResponseBody().close();
}
});
server.start();
}
@After
public void tearDown() throws Exception {
server.stop(1);
}
@Test
public void httpUrlConnection206Response() throws Exception {
String body = getContent("http://localhost:8080", 206);
assertThat(body, equalTo("I'm a 206 response"));
}
@Test(expected = AssertionError.class)
public void httpUrlConnection205Response() throws Exception {
getContent("http://localhost:8080", 205);
}
public String getContent(String url, int expectedResponseCode) throws IOException {
URL requestURL = new URL(url);
HttpURLConnection connection = (HttpURLConnection) requestURL.openConnection();
try {
connection.setRequestProperty("Connection", "close");
connection.setReadTimeout(5000);
assertEquals("Request successfully handled",
expectedResponseCode,
connection.getResponseCode());
InputStream input = connection.getInputStream();
try {
return toString(input);
} finally {
input.close();
}
} finally {
connection.disconnect();
}
}
public String toString(InputStream stream) throws IOException {
int data;
StringBuilder builder = new StringBuilder();
while ((data = stream.read()) != -1) {
builder.append((char) data);
}
return builder.toString();
}
}
这意味着您的测试是正确的,并且您的服务存在问题。