struts2 gb2312 HttpURLConnection乱码问题解决

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);
	}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值