这章先介绍HttpUrlConnection的用法,HttpUrlConnction类位于java.net包下,里面的一些参数(属性)如果不做实验,有的还真不太明白是什么意思。所以这里通过做实验,理解这些参数的含义。
这些参数属性在HttpUrlConnction中通过set*方法去设置。
设置连接参数的常用的方法:
setDoInput()
setDoOutput()
setUseCaches()
setRequestMethod()
设置请求头的方法:
setRequestProperty(key,value)
发送URL请求的方法
getOutputStream()
获取服务器的响应的方法
getContent()
getInputStream()
获取服务器响应的信息头:
getContentEncoding()
getContentLength()
getContentType()
1.简单的Http请求
先简单来个使用HttpUrlConnection发送网络请求的事例吧,在例子中我们在理解这些参数的意思,我在本机的tomcat下的webapps目录下新建了一个index.jsp,用作我们访问的网络资源,启动tomat服务。
index.jsp代码:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
String name = request.getParameter("name");
%>
<title>Insert title here</title>
</head>
<body>
我的用户名是:<%=name%>
</body>
</html>
我们知道,发送http请求有两种方式,一种是GET方式,一种是POST方式,不设置的话,默认请求方式为GET方法。
1)GET方法
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class SimpleHttpUrlConn1 {
public static void main(String[] args) {
StringBuffer strBuffer = new StringBuffer();
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
BufferedReader rufferedReader = null;
try {
URL serverUrl = new URL("http://localhost:8080/test/index.jsp?name=ccc");
httpURLConnection = (HttpURLConnection)serverUrl.openConnection();
httpURLConnection.setRequestMethod("GET");
// 设置是否从httpUrlConnection读入,默认情况下是true;
httpURLConnection.setDoInput(true);
//从页面读数据
if (HttpURLConnection.HTTP_OK == httpURLConnection
.getResponseCode()) {
inputStream = httpURLConnection.getInputStream();
rufferedReader = new BufferedReader(new InputStreamReader(
inputStream,"utf-8"));
String str = null;
while ((str = rufferedReader.readLine()) != null) {
strBuffer.append(str);
strBuffer.append("\r\n");
}
System.out.println(strBuffer);
System.out.println(httpURLConnection.getResponseMessage());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
实验结果:
利用HttpUrlConnection的getInputStream()方法,可以获取我们请求url的响应内容。
在代码中设置参数(属性),这个参数设置是否允许读取响应的内容。
httpURLConnection.setDoInput(true);
如果设置为false,下面的httpUrlConnection.getInputStrem就会报错。
下面我们介绍如果设置POST方法,这样就能认识一些新的参数(属性):
2)POST方式
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class SimpleHttpUrlConn2 {
public static void main(String[] args) {
StringBuffer strBuffer = new StringBuffer();
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
BufferedReader rufferedReader = null;
OutputStream outputStream =null;
try {
URL serverUrl = new URL("http://localhost:8080/test/index.jsp");
httpURLConnection = (HttpURLConnection)serverUrl.openConnection();
// 设定请求的方法为"POST",默认是GET
httpURLConnection.setRequestMethod("POST");
// 设置是否从httpUrlConnection读入,默认情况下是true;
httpURLConnection.setDoInput(true);
// 设置是否向httpUrlConnection输出,因为这个是post请求,
//参数要放在 http正文内,因此需要设为true, 默认情况下是false;
httpURLConnection.setDoOutput(true);
//从页面写数据
outputStream = httpURLConnection.getOutputStream();
String param = new String();
String name="test";
param="name="+name;
outputStream.write(param.getBytes());
//往页面读数据
if (HttpURLConnection.HTTP_OK == httpURLConnection
.getResponseCode()) {
inputStream = httpURLConnection.getInputStream();
rufferedReader = new BufferedReader(new InputStreamReader(
inputStream,"utf-8"));
String str = null;
while ((str = rufferedReader.readLine()) != null) {
strBuffer.append(str);
strBuffer.append("\r\n");
}
System.out.println(strBuffer);
System.out.println(httpURLConnection.getResponseMessage());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
实验结果:
利用HttpURLConnection的getOutputStream()方法获取输出流,可以像url发送请求,在例子中我们发送了数据name=”test”,jsp获取了这个数据,并展示。
在代码中有一行
httpURLConnection.setDoOutput(true);
设置是否可以向服务器发送数据请求,这个默认是false,如果需要向服务器发送数据设置为true,在POST方式中,outputStream把请求参数传给服务器。
如果有数据向服务器发送,而这个参数设置的是false,就会报如下错误。
2.请求头信息和响应头信息
我们用浏览器访问一下http://localhost:8080/test/index.jsp这个链接,看一下默认的响应头信息和请求头信息。
下面我们可以设置向服务器发送请求的头信息,以及打印服务器响应的头信息。
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class SimpleHttpUrlConn3 {
public static void main(String[] args) {
StringBuffer strBuffer = new StringBuffer();
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
BufferedReader rufferedReader = null;
OutputStream outputStream =null;
try {
URL serverUrl = new URL("http://localhost:8080/test/index.jsp");
httpURLConnection = (HttpURLConnection)serverUrl.openConnection();
// 设定请求的方法为"POST",默认是GET
httpURLConnection.setRequestMethod("POST");
// 设置是否从httpUrlConnection读入,默认情况下是true;
httpURLConnection.setDoInput(true);
//=====设置请求头信息====
//设置发送内容的类型,【表单form的enctype属性,不设置默认为application/x-www-form-urlencoded,
//可用getRequestProperty("Content-Type")取值】
httpURLConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
//告知服务器发送何种字符集
httpURLConnection.setRequestProperty("Accept-charset", "utf-8");
//告知服务器发送何种媒体类型
httpURLConnection.setRequestProperty("Accept", "text/javascript, application/javascript, "
+ "application/ecmascript, application/x-ecmascript, */*; q=0.01");
//告知服务器采用何种压缩方式
httpURLConnection.setRequestProperty("Accept-Encoding", "gzip");
//告知服务器发送何种语言
httpURLConnection.setRequestProperty("Accept-Language", "zh-CN,en-US;q=0.8,zh;q=0.5,en;q=0.3");
//保持连接
httpURLConnection.setRequestProperty("Connection","keep-alive");
httpURLConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0");
//从页面读数据
if (HttpURLConnection.HTTP_OK == httpURLConnection
.getResponseCode()) {
inputStream = httpURLConnection.getInputStream();
rufferedReader = new BufferedReader(new InputStreamReader(
inputStream,"utf-8"));
String str = null;
while ((str = rufferedReader.readLine()) != null) {
strBuffer.append(str);
strBuffer.append("\r\n");
}
//获取服务器响应内容
System.out.println(strBuffer);
//====获取服务器响应的头信息===
//服务器响应的内容的类型,对应响应头信息的Content-Type
System.out.println(httpURLConnection.getContentType());
//服务器响应的内容的编码格式(我目前见到有gzip,deflate,sdch),对应响应头信息Content-Encoding
System.out.println(httpURLConnection.getContentEncoding());
//服务器响应的内容的长度,对应响应头信息Content-Length
System.out.println(httpURLConnection.getContentLength());
System.out.println(httpURLConnection.getRequestProperty("Content-Type"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
实验结果:
text/html;charset=utf-8
null
287
application/x-www-form-urlencoded
还有几个属性简单说明一下:
setUseCaches():是否使用缓存,如果是POST方式,则需要设置为false,
setConnectTimeout():设置连接服务器超时时间(单位:毫秒)
setReadTimeout():设置从服务器读取数据超时时间(单位:毫秒)