`
gzcj
  • 浏览: 286243 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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

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

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

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics