Skip to content

Instantly share code, notes, and snippets.

@aya-eiya
Created October 8, 2012 05:09
Show Gist options
  • Save aya-eiya/3850823 to your computer and use it in GitHub Desktop.
Save aya-eiya/3850823 to your computer and use it in GitHub Desktop.
JREに同梱のcom.sun.net.httpserverを使ってHTTPのテストをする方法 ref: http://qiita.com/items/92a7d6d530d6221d407f
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static org.junit.Assert.*;
import org.junit.Test;
import com.sun.net.httpserver.*;
public class MyTests {
@Test
public void httpServer_API_test() throws Exception {
HttpServer httpServer = HttpServer. create( new InetSocketAddress("localhost" ,8080),8080);
ExecutorService httpThreadPool = Executors. newFixedThreadPool(1);
httpServer.setExecutor(httpThreadPool);
httpServer.createContext( "/" ,new HttpHandler(){
@Override
public void handle(HttpExchange exc) throws IOException {
final String response = "Hello HTTP Server" ;
exc.sendResponseHeaders(200, response.length());
OutputStream os = exc.getResponseBody();
os.write(response.getBytes());
os.close();
}
});
httpServer.start();
// なんやらかんやらテスト
httpServer.stop(1);
httpThreadPool.shutdownNow();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment