首页 > 代码库 > HttpClient

HttpClient

1. 执行过程

    1) 创建可关闭的HttpClient连接

    2) 创建与服务器交互的方法对象:GET,POST,DELETE等,需要设置headers,请求正文参数

设置请求HttpEntity内容

//1.FileEntity
File file = new File("somefile.txt");
FileEntity entity = new FileEntity(file, 
    ContentType.create("text/plain", "UTF-8"));        
HttpPost httppost = new HttpPost("http://localhost/action.do");
httppost.setEntity(entity);

//2.Html Forms,下面例子会被编码为param1=value&param2=value的形式
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("param1", "value1"));
formparams.add(new BasicNameValuePair("param2", "value2"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
HttpPost httppost = new HttpPost("http://localhost/handler.do");
httppost.setEntity(entity);

 

    3) 执行

    4)获得HttpResponse

        处理HttpEntity

//1.使用EntityUtils类,仅限数据长度小于Integer.maxLength()&&entity来自可信任的Http server
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost/");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        long len = entity.getContentLength();
        if (len != -1 && len < 2048) {
            System.out.println(EntityUtils.toString(entity));
        } else {
            // Stream content out
        }
    }
} finally {
    response.close();
}

//2.HttpEntity#getContent()或者HttpEntity#writeTo(OuputStream)方法

//3.如果需要重复读取entity内容
CloseableHttpResponse response = <...>
HttpEntity entity = response.getEntity();
if (entity != null) {
    entity = new BufferedHttpEntity(entity);
}

 

    5)关闭结果流,关闭连接

HttpClient