【问题标题】:java.net.UnknownHostException: http://localhost:8082/consume/createjava.net.UnknownHostException: http://localhost:8082/consume/create
【发布时间】:2016-06-08 15:01:10
【问题描述】:

我正在尝试向服务器发布一个 http 帖子,但在这行代码中我收到了 java.net.UnknownHostException

Socket socket = new Socket(REST_SERVICE_URI, 8082);

这是接收请求的控制器

@RequestMapping(value="AddService",method = RequestMethod.POST)
@ResponseBody
 public void addService(@ModelAttribute("servDetForm") xxxx tb) throws IOException{
    //return dataServices.addService(tb);

     Socket socket = new Socket(REST_SERVICE_URI, 8082);
     String request = "GET / HTTP/1.0\r\n\r\n";
     OutputStream os = socket.getOutputStream();
     os.write(request.getBytes());
     os.flush();

     InputStream is = socket.getInputStream();
     int ch;
     while( (ch=is.read())!= -1)
         System.out.print((char)ch);
     socket.close(); 
 }

请问我哪里错了?

【问题讨论】:

    标签: java spring sockets http spring-mvc


    【解决方案1】:

    您应该使用 URL 类,而不是使用 Socket 类。套接字需要一个主机名,如 localhost。它不理解 URL

    URL url = new URL(REST_SERVICE_URI);
    Object content = url.getContent();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-21
      • 2023-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-01
      • 2017-08-08
      • 1970-01-01
      相关资源
      最近更新 更多