我正在尝试向服务器发送 http post,但在这行代码中收到 java.net.UnknownHostException
Socket socket = new Socket(REST_SERVICE_URI, 8082);
这是接收请求的 Controller
@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 类。套接字需要一个主机名,例如 localhost。它不理解 URL
URL url = new URL(REST_SERVICE_URI);
Object content = url.getContent();
关于java.net.UnknownHostException : http://localhost:8082/consume/create,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37706212/