java 中,有时需要使用HttpURLConnection 模拟浏览器发送http请求,那么如何获取HttpURLConnection 中的响应体呢?
private static byte[] connection(HttpURLConnection huc, byte[] sendBytes, String mode) throws Exception { if (mode.equalsIgnoreCase("POST") && sendBytes != null) { huc.getOutputStream().write(sendBytes); huc.getOutputStream().flush(); huc.getOutputStream().close(); } int resCode = huc.getResponseCode(); if (resCode == HttpURLConnection.HTTP_OK) { int contentLength = huc.getContentLength(); if (contentLength > 0) { // System.out.println("httputil,contentLength:"+contentLength); // return readData(huc); return readDataFromLength(huc, contentLength); } else { return readData(huc); } } return null; } private static byte[] readData(HttpURLConnection huc) throws Exception { InputStream in = huc.getInputStream(); return FileUtils.readBytes(in); } private static byte[] readDataFromLength(HttpURLConnection huc, int contentLength) throws Exception { InputStream in = huc.getInputStream(); BufferedInputStream bis = new BufferedInputStream(in); // 数据字节数组 byte[] receData = new byte[contentLength]; int readLength = 0; // 数据数组偏移量 int offset = 0; readLength = bis.read(receData, offset, contentLength); // 已读取的长度 int readAlreadyLength = readLength; while (readAlreadyLength < contentLength) { readLength = bis.read(receData, readAlreadyLength, contentLength-readAlreadyLength); readAlreadyLength = readAlreadyLength + readLength; } return receData; }
相关推荐
//得到Cookie的所有内容,包括SESSIONID,在进行下次提交的时候 直接把这个Cookie的值设到头里头就行了 //淡然只得到SESSIONID也很简单的 ,但是有时候Set-Cookie的值有几个的 List<String> list = (List) ...
jsoup是一个Java HTML Parser。能够从URL、文件或字符串解析HTML。利用DOM traversal或CSS selectors查找和抽取数据。能够操作HTML元素,属性和文本。能够依据一个白名单过滤用户提交的内容。
httpurlconnection 获取服务器数据并解析
使用HttpURLConnection请求链接,并解析View上的json数据字符串,并且使用Handler;使用JsonObject来解析数据
调用URL对象的openConnection( )来获取HttpURLConnection对象实例: HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 设置HTTP请求使用的方法:conn.setRequestMethod("GET"); 设置连接超时,...
HttpURLConnection文件下载\httpURLConnection文件下载
JAVA代码里,HttpURLConnection获取webservice的值,包含W3C解析XML节点方法
HttpUrlConnection获取json数据
通过httpurlconnection从网络上获取一张图片,图片没有压缩,不能太大
本人原创测试了百度,搜狗,360搜索都可以获取重定向后的真实地址,直接运行就可以,也可以根据自己项目具体修改功能。java使用HttpURLConnection获取百度搜狗360搜索链接重定向真实目标链接地址url。
HttpURLConnection的demo,里面有网络请求get post 上传文件,下载文件,介绍HttpURLConnection这个类整体流程是怎样使用的,方便初学者学习
自己写了一个基于httpurlconnection和Asynctask的例子
HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();// 取得连接 conn.connect(); InputStream is = conn.getInputStream();//取得返回的InputStream bitmap = BitmapFactory....
HttpURLConnection使用总结示例源码
代码包含了httpurlconnection基本操作,一些正常的操作。
使用HttpURLConnection发送短信
java HttpURLConnection示例 HttpURLConnection工具
利用httpurlconnection加上线程获取网络上图片并在activity中显示
一个简单的例子,使用HttpURLConnection下载图片
封装httpurlconnection 自己动手丰衣足食