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);
使用doPost方式
- 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);