java - C# Windows 窗体无法访问 REST API

标签 java c# rest intellij-idea spring-boot

我使用 Spring Boot 和 IntelliJ IDEA 开发了一个 REST API。该 API 已启动并正在运行。 Postman 可以访问它并提供相关的 JSON 响应。

然后我尝试从 C# Windows 窗体应用程序访问它。我尝试将其添加为网络引用。但该按钮已被禁用。 我的代码有什么问题?

@RestController
@RequestMapping("/students")
public class StudentController {

@Autowired
private StudentService studentService;

@RequestMapping(value="/hello")
String home() {
    return "Hello World!";
}

@RequestMapping(value="getAllStudents",method = RequestMethod.GET)
public Collection<Student> getAllStudents(){
    return studentService.getAllStudents();
}

@RequestMapping(value = "/{id}",method = RequestMethod.GET)
public Student getStudentById(@PathVariable("id") int id)
{
    return studentService.getStudentById(id);
}


@RequestMapping(value = "/{id}" , method = RequestMethod.DELETE)
public void deleteStudentById(@PathVariable("id") int id)
{
studentService.removeStudentById(id);
}

如果我将 URL 指定为 localhost:8080/students/hello,JSON 响应就会到达 Visual Studio 。但无法将其添加为网络引用。

enter image description here

这个问题的解决方案是什么?

最佳答案

Visual Studio 中的 Web 引用适用于 SOAP/ASMX Web 服务。如果您要调用 REST API,那么正如 @fharreau 所评论的那样,您将需要使用 HttpClient。

该链接向您展示了如何操作,但可能难以阅读/遵循:

https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client

这个答案可能会更好

https://stackoverflow.com/a/10928807/2309376

在SO答案中,您需要将“http://www.contoso.com/”替换为您的URL“http://localhost:8080/students/hello

关于java - C# Windows 窗体无法访问 REST API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43785189/

相关文章:

python - 如何使用 Python 进行基本的 REST Post 请求?

java - 是否可以在 while 循环中分配变量?

java - 是否有可能在 Java 中有效地实现 seqlock?

c# - 强制 C# 使用 ASCII

c# - 如何配置 Ninject 以便它为每个 Controller 创建一个实例

java - 用于附加文件的 RESTeasy 客户端代码

api - 用于 REST API 的帐户设置 - 签名或证书凭据选项?

java - Java Timing Framework 中的 PropertySetter 不适用于我自己的属性

java - 使用Java运行cmd命令

c# - 如何删除 SQL 中的重复输出?