weixin_42317049
weixin_42317049
2009-06-24 16:29

http Client 出现生僻字

  • it技术
  • 互联网问答
  • IT行业问题
  • 编程语言问答
  • 计算机技术
        //cookie
        HttpSession session=request.getSession();
        Object cookie=null;
        cookie=session.getAttribute(KEY_COOKIE);  
        
        //设置header
        PostMethod method = new PostMethod(url);  
        if(cookie!=null){
            method.setRequestHeader("Cookie", ""+cookie); 
        }
        
        Enumeration en=request.getHeaderNames();
        while(en.hasMoreElements()){
            String n=(String)en.nextElement();
            String v=request.getHeader(n); 
            method.setRequestHeader(n, v); 
        }  
        method.setRequestHeader("content-length", ""+content.getBytes().length);
        
        System.out.println("[RailUtil]Request:\n" + content + "\n");
        
        //设置内容
        method.setRequestBody(content); 
        method.setRequestHeader("Content-type", "text/xml; charset=GBK");
        
        //Client
        org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient(); 
        client.getParams().setContentCharset("GBK"); 
        //设置超时 5秒
        client.setTimeout(TIMEOUT); 
        
        //发送请求
        try {
            client.executeMethod(method);
        } catch (HttpException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            throw new Exception("连接超时或信道错误",e1);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            throw new Exception("连接超时或信道错误",e1);
        } 
        
        //保存 cookie
        Header newCookieHeader = method.getResponseHeader("Set-Cookie");
        if(newCookieHeader!=null) session.setAttribute(KEY_COOKIE, newCookieHeader.getValue());
 
         //输出返回
        StringBuilder sb_res=new StringBuilder();
        InputStream bis=null;
        try{ 
            bis=method.getResponseBodyAsStream(); 
             
            byte[] bb=new byte[1024];
            int len_res=0;
            while((len_res=bis.read(bb))>0){  
                //bb = new String(bb, "GB2312").getBytes("GBK"); 
                sb_res.append(new String(bb,0,len_res));
            }
                }catch(IOException e){
            throw new Exception("读取返回信息失败",e);
        }finally{
             if(bis!=null)bis.close();
        } 

 

代码如上,应该可以看得明白。现在问题是返回的字符串,我是用xml格式存放信息,其中部分中文字被转换为生僻字,这个是什么原因呢?


问题补充:
to lovewhzlq
如何指定正确的编码呢?返回的字符串可以检测到编码方式么?
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答

为你推荐