java httpserver搭建一个http服务器并返回json数据代码
代码语言:java
所属分类:通讯
代码描述:java httpserver搭建一个http服务器并返回json数据代码
代码标签: java httpserver http 服务器 json
下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开
import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import com.sun.net.httpserver.Headers; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; public class HelloWorld { public static void main(String[] arg) throws Exception { HttpServer server = HttpServer.create(new InetSocketAddress(8001), 0); server.createContext("/post", new BasicPostHttpHandler()); // 使用默认的 excutor server.setExecutor(null); server.start(); } } class BasicPostHttpHandler implements HttpHandler{ @Override public void handle(HttpExchange httpExchange) throws IOException { InputStream is = httpExchange.getRequestBody(); String requestData = is2string(is); System.out.println("request: " + requestData); String response = "{\"pid\":\"510229197206267348\",\"pname\":\"zhangshan\"}"; // 写回这个数据就会failed // String response = "hello world"; // 若写回这个数据则没有问题 System.out.println("resp.........完整代码请登录后点击上方下载按钮下载查看
网友评论0