参考:HttpURLConnection与HttpClient浅析
1. GET请求与POST请求
HTTP协议是现在Internet上使用得最多、最重要的协议了,越来越多的Java应用程序需要直接通过HTTP协议来访问网络资源。
在介绍HttpURLConnection前,我们还是再来说一下URL请求最常用的两种方式:GET请求与POST请求。
GET请求的数据会附在URL之后(就是把数据放置在HTTP协议头中),以?分割URL和传输数据,参数之间以&相连,如:http://localhost:8080/test.do?name=test&password=123456。
GET请求发送的参数如果数据是英文字母或数字,则按原样发送,如果是空格,则转换为+,如果是中文或其他字符,则直接把字符串用BASE64加密,得出如 %E4%BD%A0%E5%A5%BD
这类似的字符串,其中%XX中的XX为该符号以16进制表示的ASCII。
POST请求的参数不是放在URL字符串里面,而是放在HTTP请求的正文内,请求的参数被封装起来以流的形式发送给服务端。
对于GET方式提交数据的大小,HTTP协议并没有硬性限制,但某些浏览器及服务器会对它进行限制,如IE对URL长度的限制是2083字节(2K+35)。理论上POST也没有限制,可传较大量的数据。
POST的安全性要比GET的安全性高。比如:通过GET提交数据,用户名和密码将明文出现在URL上,因为登录页面有可能被浏览器缓存,如果其他人查看浏览器的历史纪录,那么别人就可以拿到你的账号和密码了,除此之外,使用GET提交数据还可能会造成Cross-site request forgery(CSRF,跨站请求伪造)攻击。
一般来说,Get是向服务器索取数据的一种请求,而Post是向服务器提交数据的一种请求。
2. HttpURLConnection简介
在JDK的java.net包中已经提供了访问HTTP协议的基本功能的类:HttpURLConnection。
HttpURLConnection是Java的标准类,它继承自URLConnection,可用于向指定网站发送GET请求、POST请求。它在URLConnection的基础上提供了如下便捷的方法:
int getResponseCode(); // 获取服务器的响应代码。
String getResponseMessage(); // 获取服务器的响应消息。
String getResponseMethod(); // 获取发送请求的方法。
void setRequestMethod(String method); // 设置发送请求的方法。
3. HttpURLConnection的使用
3.1 使用GET方式访问HTTP
1 package com.qf.demo; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 import java.net.HttpURLConnection; 7 import java.net.URL; 8 9 /** 10 * GET请求示例 11 * 12 * @author 小明 13 * 14 */ 15 public class GetDemo { 16 17 public static void main(String[] args) { 18 try { 19 // 1. 得到访问地址的URL 20 URL url = new URL( 21 "http://localhost:8080/Servlet/do_login.do?username=test&password=123456"); 22 // 2. 得到网络访问对象java.net.HttpURLConnection 23 HttpURLConnection connection = (HttpURLConnection) url 24 .openConnection(); 25 /* 3. 设置请求参数(过期时间,输入、输出流、访问方式),以流的形式进行连接 */ 26 // 设置是否向HttpURLConnection输出 27 connection.setDoOutput(false); 28 // 设置是否从httpUrlConnection读入 29 connection.setDoInput(true); 30 // 设置请求方式 31 connection.setRequestMethod("GET"); 32 // 设置是否使用缓存 33 connection.setUseCaches(true); 34 // 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向 35 connection.setInstanceFollowRedirects(true); 36 // 设置超时时间 37 connection.setConnectTimeout(3000); 38 // 连接 39 connection.connect(); 40 // 4. 得到响应状态码的返回值 responseCode 41 int code = connection.getResponseCode(); 42 // 5. 如果返回值正常,数据在网络中是以流的形式得到服务端返回的数据 43 String msg = ""; 44 if (code == 200) { // 正常响应 45 // 从流中读取响应信息 46 BufferedReader reader = new BufferedReader( 47 new InputStreamReader(connection.getInputStream())); 48 String line = null; 49 50 while ((line = reader.readLine()) != null) { // 循环从流中读取 51 msg += line + "\n"; 52 } 53 reader.close(); // 关闭流 54 } 55 // 6. 断开连接,释放资源 56 connection.disconnect(); 57 58 // 显示响应结果 59 System.out.println(msg); 60 } catch (IOException e) { 61 e.printStackTrace(); 62 } 63 } 64 }
3.2 使用POST方式访问HTTP
1 package com.qf.demo; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 import java.io.OutputStream; 7 import java.net.HttpURLConnection; 8 import java.net.MalformedURLException; 9 import java.net.URL; 10 11 /** 12 * POST请求示例 13 * 14 * @author 小明 15 * 16 */ 17 public class PostDemo { 18 19 public static void main(String[] args) { 20 try { 21 // 1. 获取访问地址URL 22 URL url = new URL("http://localhost:8080/Servlet/do_login.do"); 23 // 2. 创建HttpURLConnection对象 24 HttpURLConnection connection = (HttpURLConnection) url 25 .openConnection(); 26 /* 3. 设置请求参数等 */ 27 // 请求方式 28 connection.setRequestMethod("POST"); 29 // 超时时间 30 connection.setConnectTimeout(3000); 31 // 设置是否输出 32 connection.setDoOutput(true); 33 // 设置是否读入 34 connection.setDoInput(true); 35 // 设置是否使用缓存 36 connection.setUseCaches(false); 37 // 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向 38 connection.setInstanceFollowRedirects(true); 39 // 设置使用标准编码格式编码参数的名-值对 40 connection.setRequestProperty("Content-Type", 41 "application/x-www-form-urlencoded"); 42 // 连接 43 connection.connect(); 44 /* 4. 处理输入输出 */ 45 // 写入参数到请求中 46 String params = "username=test&password=123456"; 47 OutputStream out = connection.getOutputStream(); 48 out.write(params.getBytes()); 49 out.flush(); 50 out.close(); 51 // 从连接中读取响应信息 52 String msg = ""; 53 int code = connection.getResponseCode(); 54 if (code == 200) { 55 BufferedReader reader = new BufferedReader( 56 new InputStreamReader(connection.getInputStream())); 57 String line; 58 59 while ((line = reader.readLine()) != null) { 60 msg += line + "\n"; 61 } 62 reader.close(); 63 } 64 // 5. 断开连接 65 connection.disconnect(); 66 67 // 处理结果 68 System.out.println(msg); 69 } catch (MalformedURLException e) { 70 e.printStackTrace(); 71 } catch (IOException e) { 72 e.printStackTrace(); 73 } 74 } 75 }
3.3 说明
- HttpURLConnection对象不能直接构造,需要通过URL类中的openConnection()方法来获得。
- HttpURLConnection的connect()函数,实际上只是建立了一个与服务器的TCP连接,并没有实际发送HTTP请求。HTTP请求实际上直到我们获取服务器响应数据(如调用getInputStream()、getResponseCode()等方法)时才正式发送出去。
- 对HttpURLConnection对象的配置都需要在connect()方法执行之前完成。
- HttpURLConnection是基于HTTP协议的,其底层通过socket通信实现。如果不设置超时(timeout),在网络异常的情况下,可能会导致程序僵死而不继续往下执行。
- HTTP正文的内容是通过OutputStream流写入的, 向流中写入的数据不会立即发送到网络,而是存在于内存缓冲区中,待流关闭时,根据写入的内容生成HTTP正文。
- 调用getInputStream()方法时,返回一个输入流,用于从中读取服务器对于HTTP请求的返回信息。
- 我们可以使用HttpURLConnection.connect()方法手动的发送一个HTTP请求,但是如果要获取HTTP响应的时候,请求就会自动的发起,比如我们使用HttpURLConnection.getInputStream()方法的时候,所以完全没有必要调用connect()方法。
4. HttpClient简介
在一般情况下,如果只是需要向Web站点的某个简单页面提交请求并获取服务器响应,HttpURLConnection完全可以胜任。但在绝大部分情况下,Web站点的网页可能没这么简单,这些页面并不是通过一个简单的URL就可访问的,可能需要用户登录而且具有相应的权限才可访问该页面。在这种情况下,就需要涉及Session、Cookie的处理了,如果打算使用HttpURLConnection来处理这些细节,当然也是可能实现的,只是处理起来难度就大了。
为了更好地处理向Web站点请求,包括处理Session、Cookie等细节问题,Apache开源组织提供了一个HttpClient项目,看它的名称就知道,它是一个简单的HTTP客户端(并不是浏览器),可以用于发送HTTP请求,接收HTTP响应。但不会缓存服务器的响应,不能执行HTML页面中嵌入的Javascript代码;也不会对页面内容进行任何解析、处理。
简单来说,HttpClient就是一个增强版的HttpURLConnection,HttpURLConnection可以做的事情HttpClient全部可以做;HttpURLConnection没有提供的有些功能,HttpClient也提供了,但它只是关注于如何发送请求、接收响应,以及管理HTTP连接。
5. HttpClient的使用
使用HttpClient发送请求、接收响应很简单,只要如下几步即可。
- 创建HttpClient对象。
- 如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
- 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HttpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
- 调用HttpClient对象的execute(HttpUriRequest request)发送请求,执行该方法返回一个HttpResponse。
- 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
5.1 使用GET方式访问HTTP
1 package com.qf.client; 2 3 import java.io.IOException; 4 5 import org.apache.http.HttpEntity; 6 import org.apache.http.client.ClientProtocolException; 7 import org.apache.http.client.methods.CloseableHttpResponse; 8 import org.apache.http.client.methods.HttpGet; 9 import org.apache.http.impl.client.CloseableHttpClient; 10 import org.apache.http.impl.client.HttpClientBuilder; 11 import org.apache.http.util.EntityUtils; 12 13 /** 14 * GET请求示例 15 * 16 * @author 小明 17 * 18 */ 19 public class GetDemo { 20 21 public static void main(String[] args) { 22 // 1. 创建HttpClient对象 23 CloseableHttpClient httpClient = HttpClientBuilder.create().build(); 24 // 2. 创建HttpGet对象 25 HttpGet httpGet = new HttpGet( 26 "http://localhost:8080/Servlet/do_login.do?username=test&password=123456"); 27 CloseableHttpResponse response = null; 28 try { 29 // 3. 执行GET请求 30 response = httpClient.execute(httpGet); 31 System.out.println(response.getStatusLine()); 32 // 4. 获取响应实体 33 HttpEntity entity = response.getEntity(); 34 // 5. 处理响应实体 35 if (entity != null) { 36 System.out.println("长度:" + entity.getContentLength()); 37 System.out.println("内容:" + EntityUtils.toString(entity)); 38 } 39 } catch (ClientProtocolException e) { 40 e.printStackTrace(); 41 } catch (IOException e) { 42 e.printStackTrace(); 43 } finally { 44 // 6. 释放资源 45 try { 46 response.close(); 47 httpClient.close(); 48 } catch (IOException e) { 49 e.printStackTrace(); 50 } 51 } 52 } 53 }
5.2 使用POST方式访问HTTP
1 package com.qf.client; 2 3 import java.io.IOException; 4 import java.io.UnsupportedEncodingException; 5 import java.util.ArrayList; 6 import java.util.List; 7 8 import org.apache.http.HttpEntity; 9 import org.apache.http.NameValuePair; 10 import org.apache.http.client.ClientProtocolException; 11 import org.apache.http.client.entity.UrlEncodedFormEntity; 12 import org.apache.http.client.methods.CloseableHttpResponse; 13 import org.apache.http.client.methods.HttpPost; 14 import org.apache.http.impl.client.CloseableHttpClient; 15 import org.apache.http.impl.client.HttpClientBuilder; 16 import org.apache.http.message.BasicNameValuePair; 17 import org.apache.http.util.EntityUtils; 18 19 /** 20 * POST请求测试 21 * 22 * @author 小明 23 * 24 */ 25 public class PostDemo { 26 27 public static void main(String[] args) { 28 // 1. 创建HttpClient对象 29 CloseableHttpClient httpClient = HttpClientBuilder.create().build(); 30 // 2. 创建HttpPost对象 31 HttpPost post = new HttpPost( 32 "http://localhost:8080/Servlet/do_login.do"); 33 // 3. 设置POST请求传递参数 34 List<NameValuePair> params = new ArrayList<NameValuePair>(); 35 params.add(new BasicNameValuePair("username", "test")); 36 params.add(new BasicNameValuePair("password", "12356")); 37 try { 38 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params); 39 post.setEntity(entity); 40 } catch (UnsupportedEncodingException e) { 41 e.printStackTrace(); 42 } 43 // 4. 执行请求并处理响应 44 try { 45 CloseableHttpResponse response = httpClient.execute(post); 46 HttpEntity entity = response.getEntity(); 47 if (entity != null){ 48 System.out.println("响应内容:"); 49 System.out.println(EntityUtils.toString(entity)); 50 } 51 response.close(); 52 } catch (ClientProtocolException e) { 53 e.printStackTrace(); 54 } catch (IOException e) { 55 e.printStackTrace(); 56 } finally { 57 // 释放资源 58 try { 59 httpClient.close(); 60 } catch (IOException e) { 61 e.printStackTrace(); 62 } 63 } 64 } 65 }
5.3 说明
HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性,它不仅使客户端发送HTTP请求变得容易,而且也方便了开发人员测试接口(基于Http协议的),即提高了开发的效率,也方便提高代码的健壮性。
-------------------------------------------------
针对JDK中的URLConnection连接Servlet的问题,网上有虽然有所涉及,但是只是说明了某一个或几个问题,是以FAQ的方式来解决的,而且比较零散,现在对这个类的使用就本人在项目中的使用经验做如下总结:
1:> URL请求的类别:
分为二类,GET与POST请求。二者的区别在于:
a:) get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
b:) post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
2:> URLConnection的对象问题:
URLConnection的对象,如下代码示例:
// 下面的index.jsp由<servlet-mapping>映射到
// 一个Servlet(com.quantanetwork.getClientDataServlet)
// 该Servlet的注意点下边会提到









3:> HttpURLConnection对象参数问题



















4:> HttpURLConnection连接问题:





5:> HttpURLConnection写数据与发送数据问题:

























总结:a:) HttpURLConnection的connect()函数,实际上只是建立了一个与服务器的tcp连接,并没有实际发送http请求。
无论是post还是get,http请求实际上直到HttpURLConnection的getInputStream()这个函数里面才正式发送出去。
b:) 在用POST方式发送URL请求时,URL请求参数的设定顺序是重中之重,
对connection对象的一切配置(那一堆set函数)
都必须要在connect()函数执行之前完成。而对outputStream的写操作,又必须要在inputStream的读操作之前。
这些顺序实际上是由http请求的格式决定的。
如果inputStream读操作在outputStream的写操作之前,会抛出例外:
java.net.ProtocolException: Cannot write output after reading input.......
c:) http请求实际上由两部分组成,
一个是http头,所有关于此次http请求的配置都在http头里面定义,
一个是正文content。
connect()函数会根据HttpURLConnection对象的配置值生成http头部信息,因此在调用connect函数之前,
就必须把所有的配置准备好。
d:) 在http头后面紧跟着的是http请求的正文,正文的内容是通过outputStream流写入的,
实际上outputStream不是一个网络流,充其量是个字符串流,往里面写入的东西不会立即发送到网络,
而是存在于内存缓冲区中,待outputStream流关闭时,根据输入的内容生成http正文。
至此,http请求的东西已经全部准备就绪。在getInputStream()函数调用的时候,就会把准备好的http请求
正式发送到服务器了,然后返回一个输入流,用于读取服务器对于此次http请求的返回信息。由于http
请求在getInputStream的时候已经发送出去了(包括http头和正文),因此在getInputStream()函数
之后对connection对象进行设置(对http头的信息进行修改)或者写入outputStream(对正文进行修改)
都是没有意义的了,执行这些操作会导致异常的发生。
6:> Servlet端的开发注意点:
a:) 对于客户端发送的POST类型的HTTP请求,Servlet必须实现doPost方法,而不能用doGet方法。
b:) 用HttpServletRequest的getInputStream()方法取得InputStream的对象,比如:
InputStream inStream = httpRequest.getInputStream();
现在调用inStream.available()(该方法用于“返回此输入流下一个方法调用可以不受阻塞地
从此输入流读取(或跳过)的估计字节数”)时,永远都反回0。试图使用此方法的返回值分配缓冲区,
以保存此流所有数据的做法是不正确的。那么,现在的解决办法是
Servlet这一端用如下实现:
InputStream inStream = httpRequest.getInputStream();
ObjectInputStream objInStream = new ObjectInputStream(inStream);
Object obj = objInStream.readObject();
// 做后续的处理
// 。。。。。。
// 。。。 。。。
而客户端,无论是否发送实际数据都要写入一个对象(那怕这个对象不用),如:
ObjectOutputStream objOutputStrm = new ObjectOutputStream(outStrm);
objOutputStrm.writeObject(new String("")); // 这里发送一个空数据
// 甚至可以发一个null对象,服务端取到后再做判断处理。
objOutputStrm.writeObject(null);
objOutputStrm.flush();
objOutputStrm.close();
注意:上述在创建对象输出流ObjectOutputStream时,如果将从HttpServletRequest取得的输入流
(即:new ObjectOutputStream(outStrm)中的outStrm)包装在BufferedOutputStream流里面,
则必须有objOutputStrm.flush();这一句,以便将流信息刷入缓冲输出流.如下:
ObjectOutputStream objOutputStrm = new ObjectOutputStream(new BufferedOutputStream(outStrm));
objOutputStrm.writeObject(null);
objOutputStrm.flush(); // <======此处必须要有.
objOutputStrm.close();
HttpURLConnection是基于HTTP协议的,其底层通过socket通信实现。如果不设置超时(timeout),在网络异常的情况下,可能会导致程序僵死而不继续往下执行。可以通过以下两个语句来设置相应的超时:
System.setProperty("sun.net.client.defaultConnectTimeout", 超时毫秒数字符串);
System.setProperty("sun.net.client.defaultReadTimeout", 超时毫秒数字符串);
其中: sun.net.client.defaultConnectTimeout:连接主机的超时时间(单位:毫秒)
sun.net.client.defaultReadTimeout:从主机读取数据的超时时间(单位:毫秒)
例如:
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
System.setProperty("sun.net.client.defaultReadTime
Java中可以使用HttpURLConnection来请求WEB资源。
HttpURLConnection对象不能直接构造,需要通过URL.openConnection()来获得HttpURLConnection对象,示例代码如下:



HttpURLConnection是基于HTTP协议的,其底层通过socket通信实现。如果不设置超时(timeout),在网络异常的情况下,可能会导致程序僵死而不继续往下执行。可以通过以下两个语句来设置相应的超时:
System.setProperty("sun.net.client.defaultConnectTimeout", 超时毫秒数字符串);
System.setProperty("sun.net.client.defaultReadTimeout", 超时毫秒数字符串);
其中: sun.net.client.defaultConnectTimeout:连接主机的超时时间(单位:毫秒)
sun.net.client.defaultReadTimeout:从主机读取数据的超时时间(单位:毫秒)
例如:
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
System.setProperty("sun.net.client.defaultReadTimeout", "30000");
JDK 1.5以前的版本,只能通过设置这两个系统属性来控制网络超时。在1.5中,还可以使用HttpURLConnection的父类URLConnection的以下两个方法:
setConnectTimeout:设置连接主机超时(单位:毫秒)
setReadTimeout:设置从主机读取数据超时(单位:毫秒)
例如:



需要注意的是,笔者在JDK1.4.2环境下,发现在设置了defaultReadTimeout的情况下,如果发生网络超时,HttpURLConnection会自动重新提交一次请求,出现一次请求调用,请求服务器两次的问题(Trouble)。我认为这是JDK1.4.2的一个bug。在JDK1.5.0中,此问题已得到解决,不存在自动重发现象。out", "30000");
-------------------------------------
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步