非JAVAWEB项目提供Http接口调用实现

package httptest;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.Map;

public class App {

    public static void main(String[] args) throws IOException {
        HttpServer httpServer = HttpServer.create(new InetSocketAddress(8001), 0);
        httpServer.createContext("/test", new TestHandler());
        httpServer.start();
        System.out.println("8001端口已成功启动");
    }

    static class TestHandler implements HttpHandler {

        @Override
        public void handle(HttpExchange httpExchange) throws IOException {
            //返回
            String rtn="调用成功";
            httpExchange.sendResponseHeaders(200, 0);
            //获取请求路径
            URI requestURI = httpExchange.getRequestURI();
            System.out.println("请求路径为:"+requestURI);
            //获取请求方法
            String requestMethod = httpExchange.getRequestMethod();
            System.out.println("请求方法为:"+requestMethod);
            //获取请求体
            InputStream requestBody = httpExchange.getRequestBody();
            InputStreamReader inputStreamReader = new InputStreamReader(requestBody);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            StringBuffer stringBuffer = new StringBuffer();
            String s = "";
            while ((s = bufferedReader.readLine()) != null) {
                stringBuffer.append(s.trim());
            }

            System.out.println(stringBuffer);
            //此处引入谷歌Gson框架将String转为Map方便获取参数
            Gson gson = new Gson();
            Map map = gson.fromJson(stringBuffer.toString(), new TypeToken>() {
            }.getType());
            System.out.println("请求参数为:"+map.get("cmd"));
            System.out.println("请求参数为:"+map.get("phone"));
            OutputStream responseBody = httpExchange.getResponseBody();
            responseBody.write(rtn.getBytes());
            responseBody.close();
        }
    }
}

postman模拟调用:
非JAVAWEB项目提供Http接口调用实现_第1张图片
响应结果为:
postman相应调用成功状态码200
非JAVAWEB项目提供Http接口调用实现_第2张图片
非JAVAWEB项目提供Http接口调用实现_第3张图片
注:gsonMaven依赖


  com.google.code.gson
  gson
  2.2.4

你可能感兴趣的:(Http)