在C#中调用Java程序处理网络请求,可以通过以下几种方式实现:
Java后端(Spring Boot示例):
@RestController
public class ApiController {
@GetMapping("/hello")
public String hello() {
return "Hello from Java!";
}
}
C#客户端:
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using var httpClient = new HttpClient();
var response = await httpClient.GetAsync("http://localhost:8080/hello");
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
}
}
.proto
文件,然后使用gRPC工具生成C#和Java客户端和服务端代码。定义.proto
文件:
syntax = "proto3";
package hello;
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
Java后端(Spring Boot示例):
@SpringBootApplication
public class GrpcServer {
public static void main(String[] args) {
SpringApplication.run(GrpcServer.class, args);
}
@Bean
ServerInterceptor customInterceptor() {
return new CustomInterceptor();
}
}
@Component
public class CustomInterceptor implements ServerInterceptor {
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
// 自定义拦截逻辑
return next.startCall(call, headers);
}
}
C#客户端:
using System;
using System.Threading.Tasks;
using Grpc.Net.Client;
using HelloWorld;
class Program
{
static async Task Main(string[] args)
{
using var channel = GrpcChannel.ForAddress("https://localhost:5001");
var client = new Greeter.GreeterClient(channel);
var reply = await client.SayHelloAsync(new HelloRequest { Name = "C# Client" });
Console.WriteLine("Greeting: " + reply.Message);
}
}
Java端:
public class NativeWrapper {
static {
System.loadLibrary("native-wrapper");
}
public native String hello();
public static void main(String[] args) {
NativeWrapper wrapper = new NativeWrapper();
System.out.println(wrapper.hello());
}
}
C#端:
using System;
using System.Runtime.InteropServices;
class Program
{
[DllImport("native-wrapper.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern string hello();
static void Main(string[] args)
{
string message = hello();
Console.WriteLine(message);
}
}
根据项目需求和架构选择合适的方式。如果前后端分离,推荐使用RESTful API或gRPC。如果需要在C#中直接调用Java代码,可以使用JNI。