您的位置:首页 > 理论基础 > 计算机网络

HttpURLConnection

2009-04-14 11:23 155 查看
    HttpURLConnection能构造应用程序和 URL 之间的通信链接,于是解决了我服务器向客户端主动发送消息的难题。

/**
* 给PC端发送信息
*/
private void sendMessage() {
byte[] message = new String("abc123").getBytes();//要发送的消息
OutputStream output = null;
try {
url = new URL("http://127.0.0.1:8888/server/manage");
connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "text/html");
connection.setRequestProperty("Content-type", "text/html");
connection.setRequestProperty("Cache-Control","no-cache");
output = connection.getOutputStream();//需要放到setDoOutput方法后面
output.write(message);
output.flush();
/*getResponseCode方法很重要,调用它才会将请求发送出去*/
log.info("response code:"+ connection.getResponseCode());
output.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息