`

struts2 gb2312 HttpURLConnection乱码问题解决

    博客分类:
  • java
阅读更多

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

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics