本文整理汇总了Java中com.sun.net.httpserver.HttpExchange类的典型用法代码示例。如果您正苦于以下问题:Java HttpExchange类的具体用法?Java HttpExchange怎么用?Java HttpExchange使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpExchange类属于com.sun.net.httpserver包,在下文中一共展示了HttpExchange类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: handle
import com.sun.net.httpserver.HttpExchange; //导入依赖的package包/类
@Override
public void handle(HttpExchange t) throws IOException {
Headers reqHeaders = t.getRequestHeaders();
// some small sanity check
List<String> cookies = reqHeaders.get("Cookie");
for (String cookie : cookies) {
if (!cookie.contains("JSESSIONID")
|| !cookie.contains("WILE_E_COYOTE"))
t.sendResponseHeaders(400, -1);
}
// return some cookies so we can check getHeaderField(s)
Headers respHeaders = t.getResponseHeaders();
List<String> values = new ArrayList<>();
values.add("ID=JOEBLOGGS; version=1; Path=" + URI_PATH);
values.add("NEW_JSESSIONID=" + (SESSION_ID+1) + "; version=1; Path="
+ URI_PATH +"; HttpOnly");
values.add("NEW_CUSTOMER=WILE_E_COYOTE2; version=1; Path=" + URI_PATH);
respHeaders.put("Set-Cookie", values);
values = new ArrayList<>();
values.add("COOKIE2_CUSTOMER=WILE_E_COYOTE2; version=1; Path="
+ URI_PATH);
respHeaders.put("Set-Cookie2", values);
values.add("COOKIE2_JSESSIONID=" + (SESSION_ID+100)
+ "; version=1; Path=" + URI_PATH +"; HttpOnly");
respHeaders.put("Set-Cookie2", values);
t.sendResponseHeaders(200, -1);
t.close();
}
示例2: handlePut
import com.sun.net.httpserver.HttpExchange; //导入依赖的package包/类
public void handlePut(HttpExchange t) {
if (!isAuthenticated(t)) {
Commons.writeDTO(t, new UnauthorizedDTO(), 401);
}
User user = getUser(t);
Reader reader = new InputStreamReader(t.getRequestBody());
SettingsInputDTO inputDTO = new Gson().fromJson(reader, SettingsInputDTO.class);
if (!inputDTO.isValid()) {
Commons.writeDTO(t, new BadRequestDTO(), 400);
return;
}
GlobalConfig config = inputDTO.toGlobalConfig(user);
user.setConfig(config);
Database.getStore().save(user);
Commons.writeDTO(t, new SettingsPutResponseDTO(), 200);
}
示例3: handle
import com.sun.net.httpserver.HttpExchange; //导入依赖的package包/类
/**
* Called by HttpServer when there is a matching request for the context
*/
public void handle(HttpExchange msg) {
try {
if (fineTraceEnabled) {
LOGGER.log(Level.FINE, "Received HTTP request:{0}", msg.getRequestURI());
}
if (executor != null) {
// Use application's Executor to handle request. Application may
// have set an executor using Endpoint.setExecutor().
executor.execute(new HttpHandlerRunnable(msg));
} else {
handleExchange(msg);
}
} catch(Throwable e) {
// Dont't propagate the exception otherwise it kills the httpserver
}
}
示例4: handle
import com.sun.net.httpserver.HttpExchange; //导入依赖的package包/类
@Override
public void handle (HttpExchange t)
throws IOException
{
InputStream is = t.getRequestBody();
Headers map = t.getRequestHeaders();
Headers rmap = t.getResponseHeaders();
while (is.read() != -1);
is.close();
t.sendResponseHeaders(200, -1);
HttpPrincipal p = t.getPrincipal();
if (!p.getUsername().equals("fred")) {
error = true;
}
if (!p.getRealm().equals("[email protected]")) {
error = true;
}
t.close();
}
示例5: handle
import com.sun.net.httpserver.HttpExchange; //导入依赖的package包/类
@Override
public void handle(HttpExchange t) throws IOException {
InputStream is = t.getRequestBody();
byte[] ba = new byte[BUFFER_SIZE];
int read;
long count = 0L;
while((read = is.read(ba)) != -1) {
count += read;
}
is.close();
check(count == expected, "Expected: " + expected + ", received "
+ count);
debug("Received " + count + " bytes");
t.sendResponseHeaders(200, -1);
t.close();
}
示例6: handle
import com.sun.net.httpserver.HttpExchange; //导入依赖的package包/类
public void handle(HttpExchange arg0) throws IOException {
try {
InputStream is = arg0.getRequestBody();
OutputStream os = arg0.getResponseBody();
DataInputStream dis = new DataInputStream(is);
short input = dis.readShort();
while (dis.read() != -1) ;
dis.close();
DataOutputStream dos = new DataOutputStream(os);
arg0.sendResponseHeaders(200, 0);
dos.writeShort(input);
dos.flush();
dos.close();
} catch (IOException e) {
e.printStackTrace();
error = true;
}
}
示例7: handle
import com.sun.net.httpserver.HttpExchange; //导入依赖的package包/类
@Override
public void handle(HttpExchange t) throws IOException {
// retrieve the request json data
InputStream is = t.getRequestBody();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int len;
while ((len = is.read(buffer))>0) {
bos.write(buffer, 0, len);
}
bos.close();
String data = new String(bos.toByteArray(), Charset.forName("UTF-8"));
logit("Request: \n " + data);
// pass the data to the handler and receive a response
String response = handler.handleRequest(data);
logit(" " + response);
// format and return the response to the user
t.sendResponseHeaders(200, response.getBytes(Charset.forName("UTF-8")).length);
// t.getResponseHeaders().set("Content-Type", "application/json");
t.getResponseHeaders().set("Content-Type", "application/json, charset=UTF-8");
OutputStream os = t.getResponseBody();
os.write(response.getBytes(Charset.forName("UTF-8")));
os.close();
}
示例8: doFilter
import com.sun.net.httpserver.HttpExchange; //导入依赖的package包/类
@Override
public void doFilter(HttpExchange he, Chain chain) throws IOException {
try {
System.out.println(type + ": Got " + he.getRequestMethod()
+ ": " + he.getRequestURI()
+ "\n" + HTTPTestServer.toString(he.getRequestHeaders()));
if (!isAuthentified(he)) {
try {
requestAuthentication(he);
he.sendResponseHeaders(getUnauthorizedCode(), 0);
System.out.println(type
+ ": Sent back " + getUnauthorizedCode());
} finally {
he.close();
}
} else {
accept(he, chain);
}
} catch (RuntimeException | Error | IOException t) {
System.err.println(type
+ ": Unexpected exception while handling request: " + t);
t.printStackTrace(System.err);
he.close();
throw t;
}
}
示例9: handle
import com.sun.net.httpserver.HttpExchange; //导入依赖的package包/类
public void handle(HttpExchange exchange) throws IOException {
String requestMethod = exchange.getRequestMethod();
System.out.println(requestMethod + " /post");
if (requestMethod.equalsIgnoreCase("POST")) {
String body = new BufferedReader(
new InputStreamReader(
exchange.getRequestBody()
)
).lines().collect(Collectors.joining("\n"));
String[] parts = body.split("=");
String name = null;
if (parts.length > 1) {
name = parts[1];
}
exchange.getResponseHeaders().set(Constants.CONTENTTYPE, Constants.TEXTHTML);
exchange.sendResponseHeaders(200, 0);
OutputStream responseBody = exchange.getResponseBody();
responseBody.write(Constants.getIndexHTML(name));
responseBody.close();
} else {
new NotImplementedHandler().handle(exchange);
}
}
示例10: handle
import com.sun.net.httpserver.HttpExchange; //导入依赖的package包/类
@Override
public void handle(HttpExchange he) throws IOException {
String method = he.getRequestMethod();
InputStream is = he.getRequestBody();
if (method.equalsIgnoreCase("POST")) {
String requestBody = new String(is.readAllBytes(), US_ASCII);
if (!requestBody.equals(POST_BODY)) {
he.sendResponseHeaders(500, -1);
ok = false;
} else {
he.sendResponseHeaders(200, -1);
ok = true;
}
} else { // GET
he.sendResponseHeaders(200, RESPONSE.length());
OutputStream os = he.getResponseBody();
os.write(RESPONSE.getBytes(US_ASCII));
os.close();
ok = true;
}
}
示例11: handleGet
import com.sun.net.httpserver.HttpExchange; //导入依赖的package包/类
@Override
public void handleGet(HttpExchange t) {
if (!isAuthenticated(t)) {
Commons.writeDTO(t, new UnauthorizedDTO(), 401);
return;
}
User user = getUser(t);
List<EventMessage> messages = user.getEvents();
Collections.reverse(messages);
if (messages.size() >= 10){
messages = messages.subList(0, 10);
}
UserEventDTO dto = new UserEventDTO(messages);
Commons.writeDTO(t, dto, 200);
}
示例12: handlePost
import com.sun.net.httpserver.HttpExchange; //导入依赖的package包/类
@Override
public void handlePost(HttpExchange t) {
if (!isAuthenticated(t)) {
Commons.writeDTO(t, new UnauthorizedDTO(), 401);
return;
}
User user = getUser(t);
if (InstanceManagerService.getService().hasRegisteredInstance(user)) {
Commons.writeDTO(t, new ErrorDTO(false, "Bot already running."), 500);
return;
}
InstanceManagerService.getService().start(user);
Commons.writeDTO(t, new StartControllerSuccessDTO(InstanceManagerService.getService().hasRegisteredInstance(user)), 200);
}
示例13: handle
import com.sun.net.httpserver.HttpExchange; //导入依赖的package包/类
@Override
public void handle(HttpExchange exchange) throws IOException {
count++;
try {
switch(count) {
case 0:
AuthenticationHandler.errorReply(exchange,
"Basic realm=\"realm2\"");
break;
case 1:
t1Cond1.await();
t1cond1latch.countDown();
t1cond2latch.await();
AuthenticationHandler.okReply(exchange);
break;
default:
System.out.println ("Unexpected request");
}
} catch (InterruptedException | BrokenBarrierException e) {
throw new RuntimeException(e);
}
}
示例14: getIntParameterValue
import com.sun.net.httpserver.HttpExchange; //导入依赖的package包/类
protected int getIntParameterValue(HttpExchange exchange, String param, int defaultValue)
{
int ival = defaultValue;
final String sval = getParameterValue(exchange, param);
if( sval != null && sval.length() > 0 )
{
try
{
ival = Integer.parseInt(sval);
}
catch( NumberFormatException e )
{
// ignore
}
}
return ival;
}
示例15: handle
import com.sun.net.httpserver.HttpExchange; //导入依赖的package包/类
@Override
public synchronized void handle (HttpExchange t)
throws IOException
{
byte[] buf = new byte[2048];
try (InputStream is = t.getRequestBody()) {
while (is.read(buf) != -1) ;
}
Headers map = t.getResponseHeaders();
String redirect = root + "/foo/" + Integer.toString(count);
increment();
map.add("Location", redirect);
t.sendResponseHeaders(301, -1);
t.close();
}