이전에 제가 인터넷에서 접한 것은 Java가 http 프로토콜 클라이언트를 사용하여 http 인터페이스를 호출하여 요청을 보내는 것이었지만 이제 장벽 하드웨어에 연결해야 하는 필요성을 만났습니다. Java는 서버로서 클라이언트의 http 요청을 수신 및 처리하고 해당 데이터를 반환합니다. 여기에는 참조용으로 두 가지 방법이 기록되어 있습니다.
1. 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();
}
}
}
}
2. 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();
}
}
테스트 방법은 우편 배달부, 브라우저, Apipost 또는 http 요청 자체 테스트 도구 다운로드일 수 있습니다.