java 如何实现 http协议传输

接收 手机http协议发送的数据(字节),接收原始的字节数据,并且返回字节数据(我接收的是证书文件,接收成字符串的话,证书就打不开了)

Java 6 提供了一个轻量级的纯 Java Http 服务器的实现。下面是一个简单的例子:

public static void main(String[] args) throws Exception{
 HttpServerProvider httpServerProvider = HttpServerProvider.provider();
 InetSocketAddress addr = new InetSocketAddress(7778);
 HttpServer httpServer = httpServerProvider.createHttpServer(addr, 1);
 httpServer.createContext("/myapp/", new MyHttpHandler());
 httpServer.setExecutor(null);
 httpServer.start();
 System.out.println("started");
}

static class MyHttpHandler implements HttpHandler{
 public void handle(HttpExchange httpExchange) throws IOException {
  String response = "Hello world!";
  httpExchange.sendResponseHeaders(200, response.length());
  OutputStream out = httpExchange.getResponseBody();
  out.write(response.getBytes());
  out.close();
 }
}

  然后,在浏览器中访问 http://localhost:7778/myapp/
温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-03-30
public boolean upload(FormFile file, String filePath) {
boolean flag = false;
try {
InputStream stream = file.getInputStream(); // 把文件读入
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream bos = new FileOutputStream(filePath + "/"
+ file.getFileName()); // 建立一个上传文件的输出流
// System.out.println(filePath+"/"+file.getFileName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
baos.write(buffer, 0, bytesRead); // 将文件写入服务器
}
bos.close();
stream.close();
flag = true;
} catch (Exception e) {
System.err.print(e);
}
return flag;
}
相似回答