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

HttpURLConnection

2016-04-24 23:15 519 查看
HttpURLConnection类的作用是通过HTTP协议向服务器发送请求,并可以获取服务器发回的数据。
HttpURLConnection来自于jdk,它的完整名称为:java.net.HttpURLConnection
HttpURLConnection类,没有公开的构造方法,但我们可以通过java.net.URL的openConnection方法获取一个URLConnection的实例,而HttpURLConnection是它的子类。

URL url = new URL("http://localhost:8080");
HttpURLConnection connection =  (HttpURLConnection) url.openConnection();

方法:
conn.getResponseCode():获取响应码
conn.getResponseMessage():获取响应码描述
conn.getHeaderField("Server"):获取响应头
conn.getInputStream():获取正文输入流

示例:示例简单获取服务器数据
//建立与服务器的URL对像
URL url = new URL("http://localhost:9999/day05/servlet/Servlet1");
//打开连接
HttpURLConnection con = (HttpURLConnection)url.openConnection();
//获取服务器的输入流
InputStream in = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String str = "";
while((str=br.readLine())!=null){
     System.err.println(str);
}
con.disconnect();

示例:向服务器发消息默认请求到doGet方式
URL url = new URL("http://localhost:9999/day05/index.jsp");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
//1、打开可以向服务器发消息
con.setDoOutput(true);
conn.setRequestProperty("xxx", "yyy");//发送请求头
OutputStream out = con.getOutputStream();
out.write(“name=wzhting”.getBytes());//发送正文数据

//2、获取状态码,以表示完成请求
int code = con.getResponseCode();
System.err.println(code);

示例:用POST方法
URL url = new URL("http://localhost:9999/day05/servlet/TestConnection");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
//1、设置请求方式为post
con.setRequestMethod("POST");

//可以向服务器发消息
con.setDoOutput(true);
OutputStream out = con.getOutputStream();
out.write("name=wzhting".getBytes));
//获取状态码,以表示完成请求
int code = con.getResponseCode();
System.err.println(code);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: