java.net.UnknownHostException:http:// localhost:8082 / consume / create

时间:2016-06-08 15:01:10

标签: java spring sockets http spring-mvc

我正在尝试向服务器发一个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(); 
 }

请问哪里错了?

1 个答案:

答案 0 :(得分:0)

您应该使用URL类,而不是使用Socket类。 Socket需要一个像localhost这样的主机名。它不理解URL

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