一、调用方代码
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.function.Function;
public class MainTest {
public static void main(String[] args) {
doPost();
}
public static void doPost() {
try {
URL url = new URL("http://localhost:8080/func/get");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(15000);
connection.setReadTimeout(60000);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", "application/json");
OutputStream out = connection.getOutputStream();
ByteArrayOutputStream bao = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bao);
oos.writeObject((Function<Integer, Integer> & Serializable) s -> s * s);
out.write(bao.toByteArray());
if (connection.getResponseCode() == 200) {
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
StringBuilder sbf = new StringBuilder();
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
String result = sbf.toString();
System.out.println(result);
}
} catch (Exception ignore) {
}
}
}
二、服务端代码
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.function.Function;
@RestController
@RequestMapping("func")
@Slf4j
public class FuncController {
@PostMapping("get")
@ApiOperation("get")
public Response<Integer> get(HttpServletRequest request, HttpServletResponse response) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(request.getInputStream());
Function<Integer, Integer> convertor = (Function<Integer, Integer>) ois.readObject();
System.out.println(convertor.apply(100));
return new Response<Integer>().success(convertor.apply(100));
}
}
三、结果示意图
|