weixin_42317049 2009-06-24 16:29
浏览 410
已采纳

http Client 出现生僻字

        //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条回答

  • wanghaolovezlq 2009-06-24 17:09
    关注

    [code="java"]
    import org.apache.commons.httpclient.*;
    import org.apache.commons.httpclient.methods.*;
    import org.apache.commons.httpclient.params.HttpMethodParams;

    import java.io.*;

    public class HttpClientTutorial {

    private static String url = "http://www.apache.org/";

    public static void main(String[] args) {
    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod(url);
    
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
            new DefaultHttpMethodRetryHandler(3, false));
    
    try {
      // Execute the method.
      int statusCode = client.executeMethod(method);
    
      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + method.getStatusLine());
      }
    
      // Read the response body.
      byte[] responseBody = method.getResponseBody();
    
      // Deal with the response.
      // Use caution: ensure correct character encoding and is not binary data
    

    //这里就可以设置编码得到正确的字符
    System.out.println(new String(responseBody,"utf-8"));

    } catch (HttpException e) {
      System.err.println("Fatal protocol violation: " + e.getMessage());
      e.printStackTrace();
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    } finally {
      // Release the connection.
      method.releaseConnection();
    }  
    

    }
    }

    [/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序