获取HttpURLConnection 响应体内容

本文介绍如何使用Java的HttpURLConnection类来发送HTTP请求,并详细解释了如何从响应中读取数据,包括根据内容长度选择不同的读取方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java 中,有时需要使用HttpURLConnection 模拟浏览器发送http请求,那么如何获取HttpURLConnection 中的响应体呢?

Java代码   收藏代码
  1. private static byte[] connection(HttpURLConnection huc, byte[] sendBytes,  
  2.             String mode) throws Exception {  
  3.         if (mode.equalsIgnoreCase("POST") && sendBytes != null) {  
  4.             huc.getOutputStream().write(sendBytes);  
  5.             huc.getOutputStream().flush();  
  6.             huc.getOutputStream().close();  
  7.         }  
  8.   
  9.         int resCode = huc.getResponseCode();  
  10.   
  11.         if (resCode == HttpURLConnection.HTTP_OK) {  
  12.             int contentLength = huc.getContentLength();  
  13.             if (contentLength > 0) {  
  14. //                
  15.                 System.out.println("httputil,contentLength:"+contentLength);  
  16. //              return readData(huc);  
  17.                 return readDataFromLength(huc, contentLength);  
  18.             } else {  
  19.                 return readData(huc);  
  20.             }  
  21.         }  
  22.         return null;  
  23.     }  
  24.   
  25. private static byte[] readData(HttpURLConnection huc) throws Exception {  
  26.         InputStream in = huc.getInputStream();  
  27.         return FileUtils.readBytes(in);  
  28.   
  29.     }  
  30.   
  31.     private static byte[] readDataFromLength(HttpURLConnection huc,  
  32.             int contentLength) throws Exception {  
  33.   
  34.         InputStream in = huc.getInputStream();  
  35.         BufferedInputStream bis = new BufferedInputStream(in);  
  36.   
  37.         // 数据字节数组  
  38.         byte[] receData = new byte[contentLength];  
  39.         int readLength = 0;  
  40.         // 数据数组偏移量  
  41.         int offset = 0;  
  42.   
  43.         readLength = bis.read(receData, offset, contentLength);  
  44.         // 已读取的长度  
  45.         int readAlreadyLength = readLength;  
  46.         while (readAlreadyLength < contentLength) {  
  47.             readLength = bis.read(receData, readAlreadyLength, contentLength-readAlreadyLength);  
  48.             readAlreadyLength = readAlreadyLength + readLength;  
  49.         }  
  50.   
  51.         return receData;  
  52.     }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值