Java 处理HttpPost请求,并应答返回数据的两个处理方式

之前在网上遇到的都是java通过http协议客户端去调用http接口发送请求,如今遇到对接道闸硬件的需求。java作为一个服务端接收处理客户端的http请求,返回对应的数据。这里写了两种方式仅供参考

一.Java启动内置服务器处理Http请求

package com.ruoyi.system.httpService;

import com.sun.net.httpserver.*;
import com.sun.net.httpserver.spi.HttpServerProvider;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URI;

public class HttpServerTest {
    public static void main(String[] args) throws IOException {
        /*运行服务器*/
        RunServer();
    }
    public static void RunServer() throws IOException {
        HttpServerProvider provider = HttpServerProvider.provider();
        HttpServer httpserver =provider.createHttpServer(new InetSocketAddress(8200), 100);//监听端口8200,能同时接受100个请求
        httpserver.createContext("/ais", new TestResponseHandler());
        httpserver.setExecutor(null);
        httpserver.start();
        System.out.println("启动服务器");
    }

    public static class TestResponseHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange httpExchange) throws IOException {
            InputStream ss = httpExchange.getRequestBody();
            String requestMethod = httpExchange.getRequestMethod();
            if (requestMethod.equalsIgnoreCase("POST")) {//客户端的请求是POST方法
                //设置服务端响应的编码格式,否则在客户端收到的可能是乱码
                Headers responseHeaders = httpExchange.getResponseHeaders();
                responseHeaders.set("Content-Type", "text/html;charset=utf-8");

                //在这里通过httpExchange获取客户端发送过来的消息
                URI url = httpExchange.getRequestURI();
                InputStream requestBody = httpExchange.getRequestBody();
                int count = 0;
                while (count == 0) {
                    count = requestBody.available();
                }
                byte[] b = new byte[count];
                int readCount = 0; // 已经成功读取的字节的个数
                while (readCount < count) {
                    readCount += requestBody.read(b, readCount, count - readCount);
                }
                System.out.println("请求数据"+ new String(b));

                String response = "应答数据:测试成功";
                httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.getBytes("UTF-8").length);
                OutputStream responseBody = httpExchange.getResponseBody();
                OutputStreamWriter writer = new OutputStreamWriter(responseBody, "UTF-8");
                /*写入返回的应答数据*/
                writer.write(response);
                writer.close();
                responseBody.close();
            }

        }
    }
}

二.通过接口Servlet的方式HttpServletRequest,HttpServletResponse,进行处理


import org.springframework.web.bind.annotation.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class HttpServerController {

    /**
     * post
     *
     * @param
     * @return
     */
    @PostMapping("/ais")
    public void login(HttpServletRequest httpExchange,HttpServletResponse httpServletResponse) throws IOException {

        //在这里通过httpExchange获取客户端发送过来的消息
        InputStream ss = httpExchange.getInputStream();
        int count = 0;
        while (count == 0) {
            count = ss.available();
        }
        byte[] b = new byte[count];
        int readCount = 0; // 已经成功读取的字节的个数
        while (readCount < count) {
            readCount += ss.read(b, readCount, count - readCount);
        }
        System.out.println("请求数据" + new String(b));
        String response = "测试成功this is server";

        httpServletResponse.setContentType("text/json");
        httpServletResponse.setCharacterEncoding("utf-8");
        //把返回值输出到客户端
        ServletOutputStream out = httpServletResponse.getOutputStream();
        out.write(response.getBytes());
        out.flush();


        }

    }

测试方式可以是postman,浏览器,Apipost,或者下载http 请求自测工具都是可以的。

你可能感兴趣的:(java,springboot,java,开发语言,http,网络协议)