本文介绍了java.net.UnknownHostException:http:// localhost:8082 / consume / create的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向服务器发送一个http帖子,我在代码的这一行得到一个java.net.UnknownHostException

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);

这是接收请求的控制器

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

请问哪里错了?

推荐答案

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

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

这篇关于java.net.UnknownHostException:http:// localhost:8082 / consume / create的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 08:05