struts2中的编码全部是utf-8的,但有一个地方要通过HttpURLConnection获取外部的gb2312的内容后转换成自己的内容,由于内部请求都是utf-8的,所以获取得到的都是乱码(注:如果没有经过struts2直接运行main方法则正常),后来把respone设置为gbk就可以了。
分享下代码:
public String showStockF10()
{
//System.out.println(this.getRequest().getCharacterEncoding());//UTF-8
this.getResponse().setCharacterEncoding("gbk");
String url = "http://guso.guosen.com.cn/StockInfo/Html/F10/guso_F10_" + this.stockCode + ".htm";
String html = getHtml(url,"gbk");
System.out.println(html);
this.stockHtml = html;
return SUCCESS;
}
public static String getHtml(String urlname,String coding)
{
String html = "";
try
{
URL url = new URL(urlname);
HttpURLConnection connect = (HttpURLConnection) url.openConnection();
connect.setRequestProperty("User-agent","Mozilla/4.0");
connect.connect();
InputStream is = connect.getInputStream();
StringBuffer content = new StringBuffer();
while ((is.read()) != -1)
{
int all = is.available();
byte[] b = new byte[all];
is.read(b);
content.append(new String(b, coding));
}
is.close();
url = null;
html = content.toString();
}
catch (IOException ex)
{
//ex.printStackTrace();
return "";
}
catch (Exception e)
{
System.out.println("出现错误" + e.getStackTrace());
}
return html;
}
public static void main(String[] args)
{
String url = "http://guso.guosen.com.cn/StockInfo/Html/F10/guso_F10_000002.htm";
String html = getHtml(url,"gbk");
System.out.println(html);
}
分享到:
相关推荐
HttpURLConnection文件下载\httpURLConnection文件下载
导语:个人对网络连接接触的不多,在使用时自己发现一些问题,记录一下。 正文:我在使用HttpURLConnection.getResponseCode()的时候直接报错是IOException错误,responseCode = -1。一直想不明白,同一个程序我调用...
android客户端上传数据中文乱码3中解决方案 一种HttpPost两种HTTPURLCONNECTION
HttpURLConnection的demo,里面有网络请求get post 上传文件,下载文件,介绍HttpURLConnection这个类整体流程是怎样使用的,方便初学者学习
InputStreamReader reader = new InputStreamReader(in,"gb2312"); BufferedReader read = new BufferedReader(reader); StringBuilder builder = new StringBuilder(); String str = ""; while((str...
HttpUrlConnection获取json数据
自己写了一个基于httpurlconnection和Asynctask的例子
HttpURLConnection使用总结示例源码
代码包含了httpurlconnection基本操作,一些正常的操作。
使用HttpURLConnection发送短信
java HttpURLConnection示例 HttpURLConnection工具
彻底解决android开发中,使用用HttpUrlConnection与web服务器之间session保持问题
一个简单的例子,使用HttpURLConnection下载图片
封装httpurlconnection 自己动手丰衣足食
远程连接服务器HttpURLConnection,该工具有上传到远程服务器的方法,供参考远程连接服务器HttpURLConnection,该工具有上传到远程服务器的方法,供参考
HttpURLConnection用法详解, 轻松掌握HttpURLConnection开发原理
NULL 博文链接:https://lydia-fly.iteye.com/blog/2033391
在 Android 中对 HttpURLConnection 的简单使用,仅供参考。
java网络请求工具类 HttpURLConnection post请求工具类HttpURLConnection httpURLConnection = (HttpURLConnection) url .openConnection(); httpURLConnection.setRequestMethod("POST");// 提交模式
主要介绍了JAVA通过HttpURLConnection 上传和下载文件的方法,非常具有实用价值,需要的朋友可以参考下