爬虫基础之URI访问网站获取HTML
GET方式
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class JDKGet {
public static void main(String[] args) throws Exception {
//1.创建URL对象
URL url = new URL("http://www.bingosoft.net");
//2. 获取连接
HttpURLConnection httpURLConnection =(HttpURLConnection) url.openConnection();
//3. 封装参数
//3.1 指定请求的方式
// 注意: 参数的值一定要大写
httpURLConnection.setRequestMethod("GET");
//4. 获取数据的操作(获取响应体)
InputStream in = httpURLConnection.getInputStream();
//5. 获取内容
int len = -1;
byte[] b = new byte[1024];
while((len = in.read(b))!=-1){
System.out.println(new String(b,0,len));
}
}
}
POST方式
public class JDKPost {
public static void main(String[] args) throws IOException {
//1.设置连接
URL url = new URL("http://www.bingosoft.net");
//2.打开连接
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
//3.设置请求参数
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
//3.1封装请求参数
OutputStream outputStream = urlConnection.getOutputStream();
outputStream.write("username=zs&password=123".getBytes());
//4.获取数据
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String len = null;
while ((len = br.readLine()) != null){
System.out.println(len);
}
//5.关闭资源
br.close();
outputStream.close();
}
}
