本文整理汇总了Java中com.sun.net.httpserver.HttpExchange.getRequestBody方法的典型用法代码示例。如果您正苦于以下问题:Java HttpExchange.getRequestBody方法的具体用法?Java HttpExchange.getRequestBody怎么用?Java HttpExchange.getRequestBody使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.sun.net.httpserver.HttpExchange
的用法示例。
在下文中一共展示了HttpExchange.getRequestBody方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: handle
import com.sun.net.httpserver.HttpExchange; //导入方法依赖的package包/类
@Override
public void handle(HttpExchange httpExchange) throws IOException {
StringBuilder body = new StringBuilder();
try (InputStreamReader reader = new InputStreamReader(httpExchange.getRequestBody(), Consts.UTF_8)) {
char[] buffer = new char[256];
int read;
while ((read = reader.read(buffer)) != -1) {
body.append(buffer, 0, read);
}
}
Headers requestHeaders = httpExchange.getRequestHeaders();
Headers responseHeaders = httpExchange.getResponseHeaders();
for (Map.Entry<String, List<String>> header : requestHeaders.entrySet()) {
responseHeaders.put(header.getKey(), header.getValue());
}
httpExchange.getRequestBody().close();
httpExchange.sendResponseHeaders(statusCode, body.length() == 0 ? -1 : body.length());
if (body.length() > 0) {
try (OutputStream out = httpExchange.getResponseBody()) {
out.write(body.toString().getBytes(Consts.UTF_8));
}
}
httpExchange.close();
}
示例2: handle
import com.sun.net.httpserver.HttpExchange; //导入方法依赖的package包/类
public void handle(Pair<String, String> id, HttpExchange he, String[] path) throws Exception {
Handler handler = handlers.get(id);
if (handler == null) {
// logger.log(Level.SEVERE, "Missing handler: {0}", id);
handler = handlers.get(null);
}
if (!handler.validate(he.getRequestHeaders(), path)) {
he.getResponseHeaders().set("WWW-Authenticate", "Basic realm=\"TurtleAPI\"");
handler.sendResponse(he, 401, "{\"err\":\"Unauthorized\"}");
// logger.log(Level.SEVERE, "Unauthorized");
return;
}
try (OutputStream out = he.getResponseBody()) {
try (InputStream in = he.getRequestBody()) {
handler.handle(he, in, out, path);
}
}
}
示例3: 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();
}
示例4: handle
import com.sun.net.httpserver.HttpExchange; //导入方法依赖的package包/类
@Override
public void handle(HttpExchange exchange) throws IOException {
InputStream inputStream = exchange.getRequestBody();
String query;
String response;
try (Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name())) {
query = scanner.useDelimiter("\\A").next();
logger.info("Query: " + query);
inputStream.close();
response = queryServer(query, ReturnType.JSON);
} catch (Exception e) {
logger.info("ERROR", e);
response = new Message("ERROR: " + e.getMessage(), true).toJson().toString();
}
// Add the header to avoid error:
// “No 'Access-Control-Allow-Origin' header is present on the requested resource”
Headers responseHeaders = exchange.getResponseHeaders();
responseHeaders.add("Access-Control-Allow-Origin", "*");
exchange.sendResponseHeaders(200, response.length());
OutputStream outputStream = exchange.getResponseBody();
outputStream.write(response.getBytes());
outputStream.close();
}
示例5: 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();
}
示例6: handle
import com.sun.net.httpserver.HttpExchange; //导入方法依赖的package包/类
@Override
public void handle(HttpExchange exchange) throws IOException {
String requestBody;
try (BufferedReader br = new BufferedReader(new InputStreamReader(exchange.getRequestBody(), "utf-8"))) {
requestBody = br.lines().collect(Collectors.joining(System.lineSeparator()));
}
System.out.println("[x] Received body: \n" + requestBody);
String response = "Hello from demo client!";
exchange.sendResponseHeaders(200, response.length());
System.out.println("[x] Sending response: \n" + response);
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
示例7: 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();
}
示例8: 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;
}
}
示例9: 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;
}
}
示例10: handle
import com.sun.net.httpserver.HttpExchange; //导入方法依赖的package包/类
@Override
public void handle(HttpExchange t) throws IOException {
InputStream is = t.getRequestBody();
byte[] ba = new byte[8192];
while(is.read(ba) != -1);
t.sendResponseHeaders(200, RESP_LENGTH);
try (OutputStream os = t.getResponseBody()) {
os.write(new byte[RESP_LENGTH]);
}
t.close();
}
示例11: main
import com.sun.net.httpserver.HttpExchange; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
boolean error = true;
// Start a dummy server to return 404
HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
HttpHandler handler = new HttpHandler() {
public void handle(HttpExchange t) throws IOException {
InputStream is = t.getRequestBody();
while (is.read() != -1);
t.sendResponseHeaders (404, -1);
t.close();
}
};
server.createContext("/", handler);
server.start();
// Client request
try {
URL url = new URL("http://localhost:" + server.getAddress().getPort());
String name = args.length >= 2 ? args[1] : "foo.bar.Baz";
ClassLoader loader = new URLClassLoader(new URL[] { url });
System.out.println(url);
Class c = loader.loadClass(name);
System.out.println("Loaded class \"" + c.getName() + "\".");
} catch (ClassNotFoundException ex) {
System.out.println(ex);
error = false;
} finally {
server.stop(0);
}
if (error)
throw new RuntimeException("No ClassNotFoundException generated");
}
示例12: handle
import com.sun.net.httpserver.HttpExchange; //导入方法依赖的package包/类
public void handle(HttpExchange t) throws IOException {
InputStream is = t.getRequestBody();
Headers map = t.getRequestHeaders();
Headers rmap = t.getResponseHeaders();
URI uri = t.getRequestURI();
debug("Server: received request for " + uri);
String path = uri.getPath();
if (path.endsWith("a.jar"))
aDotJar++;
else if (path.endsWith("b.jar"))
bDotJar++;
else if (path.endsWith("c.jar"))
cDotJar++;
else
System.out.println("Unexpected resource request" + path);
while (is.read() != -1);
is.close();
File file = new File(docsDir, path);
if (!file.exists())
throw new RuntimeException("Error: request for " + file);
long clen = file.length();
t.sendResponseHeaders (200, clen);
OutputStream os = t.getResponseBody();
FileInputStream fis = new FileInputStream(file);
try {
byte[] buf = new byte [16 * 1024];
int len;
while ((len=fis.read(buf)) != -1) {
os.write (buf, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
fis.close();
os.close();
}
示例13: handle
import com.sun.net.httpserver.HttpExchange; //导入方法依赖的package包/类
public void handle (HttpExchange t) throws IOException {
InputStream is = t.getRequestBody();
while (is.read () != -1) ;
is.close();
t.sendResponseHeaders(200, -1);
HttpPrincipal p = t.getPrincipal();
if (!p.getUsername().equals(USERNAME)) {
error = true;
}
if (!p.getRealm().equals(REALM)) {
error = true;
}
t.close();
}
示例14: handle
import com.sun.net.httpserver.HttpExchange; //导入方法依赖的package包/类
@Override
public void handle(HttpExchange t) throws IOException {
try {
InputStream is = t.getRequestBody();
StringWriter writer = new StringWriter();
IOUtils.copy(is, writer, "UTF-8");
String theString = writer.toString();
List<NameValuePair> params = URLEncodedUtils.parse(theString, Charset.forName("UTF-8"));
IridiumMessage message = new IridiumMessage(params);
logger.debug(message);
if (message.data == null || message.data.isEmpty()) {
logger.info(MessageFormat.format("Empty MO message received ''{0}''.", message.toString()));
} else if (message.imei.equalsIgnoreCase(imei)) {
MAVLinkPacket packet = message.getPacket();
if (packet != null) {
MAVLinkLogger.log(Level.INFO, "MO", packet);
dst.sendMessage(packet);
} else {
logger.warn(MessageFormat.format("Invalid MAVLink message ''{0}''.", message.toString()));
}
} else {
logger.warn(MessageFormat.format("Invalid IMEI ''{0}''.", message.imei));
}
//Send response
String response = "";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
} catch (DecoderException e) {
logger.error(e.getMessage());
throw new IOException(e.getMessage());
}
}
示例15: handle
import com.sun.net.httpserver.HttpExchange; //导入方法依赖的package包/类
public void handle(HttpExchange t)
throws IOException {
InputStream is = t.getRequestBody();
Headers map = t.getRequestHeaders();
Headers rmap = t.getResponseHeaders();
OutputStream os = t.getResponseBody();
URI uri = t.getRequestURI();
String path = uri.getPath();
while (is.read() != -1) ;
is.close();
File f = new File(_docroot, path);
if (!f.exists()) {
notfound(t, path);
return;
}
String method = t.getRequestMethod();
if (method.equals("HEAD")) {
rmap.set("Content-Length", Long.toString(f.length()));
t.sendResponseHeaders(200, -1);
t.close();
} else if (!method.equals("GET")) {
t.sendResponseHeaders(405, -1);
t.close();
return;
}
if (path.endsWith(".html") || path.endsWith(".htm")) {
rmap.set("Content-Type", "text/html");
} else {
rmap.set("Content-Type", "text/plain");
}
t.sendResponseHeaders (200, f.length());
FileInputStream fis = new FileInputStream(f);
int count = 0;
try {
byte[] buf = new byte[16 * 1024];
int len;
while ((len = fis.read(buf)) != -1) {
os.write(buf, 0, len);
count += len;
}
} catch (IOException e) {
e.printStackTrace();
}
fis.close();
os.close();
}