通过HttpURLConnection获得网页源代码
来源:互联网 发布:mac新版itunes添加铃声 编辑:程序博客网 时间:2024/04/30 03:58
找了一个网络上的来使用
结果出现某个位置上的字符的UTF-8的中文乱码问题
关键之处是在IO的时候指定编码,而不是在读取的时候指定
/** * 获取网络的响应,判断并返回 * @param urlStr * @return String */public String getFetionMsgWML(String urlStr) {String urlContent = null;//InputStream in = null;//OutputStream out = null;HttpURLConnection httpUrlCon = null;BufferedReader in = null;StringBuffer sb = new StringBuffer("");try {URL url = new URL(urlStr);httpUrlCon = (HttpURLConnection)url.openConnection();//建立连接//httpUrlCon.setDoInput(true);//httpUrlCon.setDoOutput(true);httpUrlCon.setRequestMethod("GET");//httpUrlCon.setRequestProperty("Charset", "UTF-8");//1.使用HttpURLConnection要记得释放IO资源,尤其是当调用getContentLength()方法获得文件长度,// 这时其实已经隐含的打开了io需要我们手动的再获得一次inputstream,然后在关闭这个inputstream。//2.使用HttpURLConnection时要注意设置超时,有两个设置方法setConnectTimeout()和setReadTimeout()这两个一定要设置,// 尤其是多次大量进行连接的时候更要设置这两个方法,否则容易造成程序在读某个连接的时候僵死在那,导致程序无法继续进行.httpUrlCon.setConnectTimeout(30000);httpUrlCon.setReadTimeout(30000);int code=httpUrlCon.getResponseCode();if(code!= HttpURLConnection.HTTP_OK){ System.out.println("***********wap 连接飞信消息盒子失败************** "); System.out.println("*********** code: " + code); System.out.println("*********** url: " + urlStr);}if(code == HttpURLConnection.HTTP_OK){String inputLine = null;in = new BufferedReader(new InputStreamReader(httpUrlCon.getInputStream(),"UTF-8"));//注意,此处UTF-8while((inputLine = in.readLine()) != null) {sb.append(inputLine);}}} catch (Exception e) {System.out.println("***********wap 连接飞信消息盒子失败 ************** ");System.out.println("*********** url: " + urlStr);e.printStackTrace();} finally {try {if(null != in){in.close();}} catch (Exception e) {}if (null != httpUrlCon){httpUrlCon.disconnect();}}urlContent = sb.toString();//urlContent.replaceAll("&", "&");return urlContent;}
- 通过HttpURLConnection获得网页源代码
- java获得网页源代码
- 通过HttpURLConnection获取网页信息
- 使用python在win下通过IE组件获得Ajax执行后网页源代码
- PHP抓取网页内容获得网页源代码
- PHP抓取网页内容获得网页源代码
- 通过开源代码查看网页源代码
- HttpURLConnection getHeaderFields().get("Content-Type") 获得网页编码问题
- 通过HttpURLConnection获得服务器的数据简单模型
- Delphi中POST方法获得网页源代码
- C#获得指定网页的源代码
- ASP用xmlhttp获得网页源代码
- 关于爬虫的,获得网页源代码
- 通过代理抓取网页code方法 proxy httpurlconnection
- JS 获得网页代码 远程网页源代码读取
- VC++通过HTTP方式获取网页源代码
- 通过WebView获取访问网页的源代码
- 利用WebClient和WebRequest类获得网页源代码
- c++多线程(二)
- Java对象持久化技术Hibernate入门之一
- Mapreduce for Machine Learning
- poj 1094 Sorting It All Out 拓扑排序
- HDU 3987 最小割模型
- 通过HttpURLConnection获得网页源代码
- C++ 声明对象
- sed用法,替换文本内容用于修改主机名
- 第八章 OpenGL层
- Java对象持久化技术之Hibernate入门之二
- c++中,什么时候用 A a;和什么时候用A a=new A;
- Linux下获得主机与域名-gethostbyname和gethostbyaddr
- 软件项目管理的十大定律
- 设计模式与实例代码:Observer模式