httpclient 学习笔记

前阵子,学习了一下APACHE 的httpclient,感觉httpclient还是比较好用的,就是传输汉字的时候有默认的编码问题。

 

 

在使用 httpClient.executeMethod(PostMethod);时,httpclient会调用

  protected RequestEntity generateRequestEntity() {
        if (!this.params.isEmpty()) {
            // Use a ByteArrayRequestEntity instead of a StringRequestEntity.
            // This is to avoid potential encoding issues.  Form url encoded strings
            // are ASCII by definition but the content type may not be.  Treating the content
            // as bytes allows us to keep the current charset without worrying about how
            // this charset will effect the encoding of the form url encoded string.
            String content = EncodingUtil.formUrlEncode(getParameters(), getRequestCharSet());
            ByteArrayRequestEntity entity = new ByteArrayRequestEntity(
                EncodingUtil.getAsciiBytes(content),
                FORM_URL_ENCODED_CONTENT_TYPE
            );
            return entity;
        } else {
            return super.generateRequestEntity();
        }
    }

 

在此时会对内容进行编码。

解决编码的问题可以如下进行

1.使用httpClient.getParams().setContentCharset()

该函数即可对传输的内容进行自己想要的编码。

 

2.另外,如果想避免编码问题,可以使用流传输

 httppost.setRequestEntity(new InputStreamRequestEntity(
        inputstream));

使用流传输内容的方法即可避免传输内容时被编码的问题。

使用流传输的时候发现输入的什么,内容就是什么,没有被编码。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值