HttpClient请求网址返回javascript乱码

实现代码如下:

public static String getHtml() { 
        String response = ""; 
        HttpClient client = new HttpClient(); 
        HttpMethod method = new GetMethod("http://static1.mtime.cn/Utility/Data/TheaterListBoxData.m");
        try { 
                client.executeMethod(method); 
                if (method.getStatusCode() == HttpStatus.SC_OK) { 
                        System.out.println(method.getResponseBodyAsString());
//                        response = method.getResponseBodyAsString(); 
                } 
        } catch (URIException e) { 
                e.printStackTrace();
                return null;
        } catch (IOException e) { 
                e.printStackTrace();
                return null;
        } finally 
        { 
                method.releaseConnection(); 
        }
        
        return response; 

    }

 请求这个路径http://static1.mtime.cn/Utility/Data/TheaterListBoxData.m就有问题,因为返回的是text/javascript;

看到别人说说method.getResponseBodyAsStream()返回流,再设置流的字符编码,循环读取出来的也是乱码!

求解决方案!

 

因为response的流是gzip的,转一下就好了。

[code="java"]
InputStream is = new GZIPInputStream(method.getResponseBodyAsStream());

System.out.println(IOUtils.toString(is));

[/code]

提交请求前添加mehtod.setRequestHeader("Content-type", "text/javascript");

是字符编码的问题,如果你没有指定编码,那么如果你在windows下面运行的话,从byte[]变成String的时候,使用的是系统默认的编码,在WINDOWS下面,中文系统的编码默认是GBK,而你给的网址的JS采用的是UTF-8的编码,这个时候,当然就有乱码了。

最后推荐你使用最新的httpclient,你使用的是3.x的,最新的4.x在易用性方面以及架构方面都有很大的进步,你可以尝试一下。

Reader reader=new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(),"编码格式"));//指定编码格式