一、HttpURLConnection发送GET请求
public static void GETRequest(int page,String cookie) throws Exception {
String url = String.format("http://www.baidu.com/user?tn=baidu&pn=%s",page);
//创建远程url连接对象
URL obj = new URL(url);
//通过远程url对象打开一个连接,强制转换为HttpUrlConnection类型
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//默认值我GET
con.setRequestMethod("GET");
con.setConnectTimeout(15000); //设置连接主机服务器超时时间:15000毫秒
con.setReadTimeout(60000); //设置读取远程返回的数据时间:60000毫秒
con.setDoInput(true); //设置输入流采用字节流
con.setDoOutput(true); //设置输出流采用字节流
//添加请求头
con.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10.5; zh-CN; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15");
con.setRequestProperty("Host", "www.baidu.com");
// con.setRequestProperty("Accept-Encoding","gzip, deflate");
con.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
con.setRequestProperty("Connection", "keep-alive");
con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
con.setRequestProperty("Cookie", cookie);
// 状态码,getResponseCode()隐形调用了httpConn.connect()
int responseCode = con.getResponseCode();
System.out.println("Sending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream(), "gb2312"));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
System.out.println(response);
in.close();
}
二、HttpURLConnection发送POST请求
public static void POSTRequest(String cookie) throws IOException {
String param = "username=admin&password=admin";
String url = "http://www.baidu.com/user/userlogin";
//创建远程url连接对象
URL obj = new URL(url);
//通过远程url对象打开一个连接,强制转换为HttpUrlConnection类型
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//默认值我GET
con.setRequestMethod("POST");
con.setConnectTimeout(15000); //设置连接主机服务器超时时间:15000毫秒
con.setReadTimeout(60000); //设置读取远程返回的数据时间:60000毫秒
con.setDoInput(true); //设置输入流采用字节流
con.setDoOutput(true); //设置输出流采用字节流
//添加请求头
con.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10.5; zh-CN; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15");
con.setRequestProperty("Host", "www.baidu.com");
// con.setRequestProperty("Accept-Encoding","gzip, deflate");
con.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
con.setRequestProperty("Connection", "keep-alive");
con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
con.setRequestProperty("Cookie", cookie);
OutputStream output = con.getOutputStream();
//写入参数输出流
output.write(param.getBytes());
OutputStreamWriter outr = new OutputStreamWriter(output, StandardCharsets.UTF_8);
outr.flush();
outr.close();
//状态码
int responseCode = con.getResponseCode();
System.out.println("Sending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//打印结果
System.out.println(response.toString());
}
三、关于respond中set-cookie值的获取
- 在HttpURLConnection中t常用两个方法获得响应中的header,getHeaderField()方法仅限于获取header中的不重复项,例如某个响应中的set-cookie有多个值,那么getHeaderField()方法仅返回最后一个set-cookie的值,那么此时我们可以使用getHeaderFields()方法,此方法返回一个Map,其包含所有的header中的数据
/**
Returns the value of the named header field.
If called on a connection that sets the same header multiple times with possibly different values, only the last value is returned.
Params:
name – the name of a header field.
Returns:
the value of the named header field, or null if there is no such field in the header.
**/
public String getHeaderField(String name);
/**
Returns an unmodifiable Map of the header fields. The Map keys are Strings that represent the response-header field names. Each Map value is an unmodifiable List of Strings that represents the corresponding field values.
Returns:
a Map of header fields
**/
public Map<String,List<String>> getHeaderFields()
四、HttpURLConnection乱码问题
在HttpURLConnection中出现乱码的情况主要有两种,我们需要定位乱码出现在哪个位置再解决,这个问题其他博主都写过很多的解决方法,这里不再详细说明。但是我在向一个比较古老的php发送请求时,返回的html内容乱码,我在将header中的Accept-Encoding注释掉以后,返回内容奇迹般的恢复了正常,使用各种方法都不能解决响应乱码的兄弟们可以试试
版权声明:本文为weixin_43919656原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。