一、文章前言
一念之间的坚持换来更好的自己
u=84224111,892651579&fm=27&gp=0.jpg二、内容:
有时候我们需要用java代码模仿浏览器给某个服务器发送http请求(本文将以get和post请求来展示)。
1、首先我们先来看看get请求(文章所请求得服务器就以百度搜索为例):
1.我们打开百度主页按下F12或者右键查看网页源码NetWork
2.可以简单的发现请求url是"https://www.baidu.com/s?wd=(这里是你想查询的东西也就是get请求的参数)"
下面放上代码
private static StringBuilder buildConnection() throws IOException {
//String path = "https://www.baidu.com/s?wd=(...)";根据实际情况来
String path = "https://www.reg007.com/search?q=xxxx@qq.com";
URL url;
HttpURLConnection connection;
url = new URL(path);
connection = (HttpURLConnection) url.openConnection();
//设置请求的方式
connection.setRequestMethod("GET");
connection.connect();
//获取请求返回的输入流
InputStream inputStream = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(reader);
StringBuilder result = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
result.append(line);
}
connection.disconnect();
bufferedReader.close();
inputStream.close();
reader.close();
return result;
}
方法运行结果:
获取到了网页的源码(可以给利用jsoup当成爬虫使用)
**2、下面是post请求
代码如下:
private static StringBuilder buildConnection() throws IOException {
//String path = "https://www.baidu.com/s?wd=(...)";根据实际情况来
String path = "";
URL url;
HttpURLConnection connection;
url = new URL(path);
connection = (HttpURLConnection) url.openConnection();
//设置请求的方式
connection.setRequestMethod("POST");
//post请求必须设置下面两行
connection.setDoInput(true);
connection.setDoOutput(true);
/**
* JSON数据的请求
* outputStream.write(stringJson.getBytes(), 0, stringJson.getBytes().length);
* outputStream.close();
* **/
OutputStream outputStream = connection.getOutputStream();
DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
String username= "";
String password = "";
String content = "username=" + username + "&password=" + password;
dataOutputStream.writeBytes(content);
dataOutputStream.flush();
dataOutputStream.close();
connection.connect();
//获取请求返回的输入流
InputStream inputStream = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(reader);
StringBuilder result = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
result.append(line);
}
connection.disconnect();
bufferedReader.close();
inputStream.close();
reader.close();
return result;
}
以上代码就不给测试了因为post请求测起来就需要一些个人的信息了,为了防止信息泄露。
如果读者有什么问题请在评论区留言。
(如果有不正确的地方请指正)
网友评论