当前位置: 首页>>代码示例>>Java>>正文


Java HttpExchange类代码示例

本文整理汇总了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();
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:32,代码来源:HttpOnly.java

示例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);
}
 
开发者ID:Twasi,项目名称:twasi-core,代码行数:21,代码来源:SettingsController.java

示例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
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:20,代码来源:WSHttpHandler.java

示例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();
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:20,代码来源:Deadlock.java

示例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();
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:20,代码来源:FixedLengthInputStream.java

示例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;
        }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:25,代码来源:B6401598.java

示例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();
	}
 
开发者ID:SimplifiedLogic,项目名称:creoson,代码行数:28,代码来源:JshellHttpHandler.java

示例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;
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:27,代码来源:HTTPTestServer.java

示例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);
    }
}
 
开发者ID:zupzup,项目名称:java-0-deps-webapp,代码行数:24,代码来源:WebApp.java

示例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;
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:22,代码来源:MultiAuthTest.java

示例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);
}
 
开发者ID:Twasi,项目名称:twasi-core,代码行数:19,代码来源:UserEventsController.java

示例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);
}
 
开发者ID:Twasi,项目名称:twasi-core,代码行数:19,代码来源:StartController.java

示例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);
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:23,代码来源:B4769350.java

示例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;
}
 
开发者ID:equella,项目名称:Equella,代码行数:18,代码来源:AbstractDispatchHandler.java

示例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();
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:17,代码来源:SmokeTest.java


注:本文中的com.sun.net.httpserver.HttpExchange类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。