介绍

项目中经常使用java进行http的访问,一般都使用apache的http client库来进行http请求。这次主要学习下使用jdk原生代码来进行http请求,分别学习get和post请求。

JDK原生类

JDK提供了用于发送http请求的类:

  • URL : 代表一个统一资源定位符。
  • URI : 表示一个统一资源标识符 (URI) 引用。
  • URLConnection : 抽象类 URLConnection ,它代表应用程序和 URL 之间的通信链接。
  • HttpURLConnection : 支持 HTTP 特定功能的 URLConnection。

GET请求

GET请求代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@Test
public void get() throws IOException
{
URL url = new URL("http://www.baidu.com");

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setRequestMethod("GET");
connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setConnectTimeout(5000);

System.out.println(connection.getResponseCode());
System.out.println(connection.getResponseMessage());

InputStream in = connection.getInputStream();

BufferedReader bd = new BufferedReader(new InputStreamReader(in));

String line = "";

while ((line = bd.readLine()) != null)
{
System.out.println(line);
}

in.close();

bd.close();
}

如果是带请求参数的get请求,直接添加到URL上即可。如http://www.baidu.com?name=1这样。

POST请求

POST请求代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
@Test
public void post() throws Exception
{
String parameterData = "username=rcx&password=rcx";

URL url = new URL("http://localhost:8080/login");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", String.valueOf(parameterData.length()));

OutputStream outputStream = connection.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);

outputStreamWriter.write(parameterData);
outputStreamWriter.flush();

InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

String line = "";

while ((line = reader.readLine()) != null)
{
System.out.println(line);
}

outputStreamWriter.close();
outputStream.close();
reader.close();
inputStream.close();
}

总结

基本上使用原生的JDK发起http请求的代码是很臃肿的,所以我们都会使用http client框架来进行http请求,以后详细分析http client是如何对原生JDK进行封装的,并且学习如何设计一个库代码。

—EOF—