java.net.UnknownHostException: http://localhost:80

2019-09-12 20:55发布

问题:

I am trying to make a http post to the server and I am getting a java.net.UnknownHostException at this line of the code

Socket socket = new Socket(REST_SERVICE_URI, 8082);

this is the controller that receives the request

@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(); 
 }

Please where is my wrong?

回答1:

Instead of using Socket class, you should use URL class. Socket requires a host name like localhost. It does not understand URL

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