HttpClient4.5 Apache 教程 [记录]

来源:互联网 发布:qq飞车神影官方数据 编辑:程序博客网 时间:2024/05/16 09:19

教程网址:
http://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/index.html

httpclient获取地址:
http://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient/4.5.4


maven:

<!-- httpclient --><dependency>    <groupId>org.apache.httpcomponents</groupId>    <artifactId>httpclient</artifactId>    <version>4.5.4</version></dependency><!-- httpclient流式API --><dependency>  <groupId>org.apache.httpcomponents</groupId>  <artifactId>fluent-hc</artifactId>  <version>4.5.4</version></dependency>

gradle:

// httpclientcompile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.4'// httpclient流式APIcompile 'org.apache.httpcomponents:fluent-hc:4.5.4'

httpclient快速开始:
http://hc.apache.org/httpcomponents-client-4.5.x/quickstart.html

// HttpClient 本地API

// getCloseableHttpClient httpclient = HttpClients.createDefault();HttpGet httpGet = new HttpGet("http://targethost/homepage");CloseableHttpResponse response1 = httpclient.execute(httpGet);try {    System.out.println(response1.getStatusLine());    HttpEntity entity1 = response1.getEntity();    // 获取输入流,进而操作,即可处理请求信息    entity1.getInputStream();    EntityUtils.consume(entity1);} finally {    response1.close();}// postHttpPost httpPost = new HttpPost("http://targethost/login");List <NameValuePair> nvps = new ArrayList <NameValuePair>();nvps.add(new BasicNameValuePair("username", "vip"));nvps.add(new BasicNameValuePair("password", "secret"));httpPost.setEntity(new UrlEncodedFormEntity(nvps));CloseableHttpResponse response2 = httpclient.execute(httpPost);try {    System.out.println(response2.getStatusLine());    HttpEntity entity2 = response2.getEntity();    // 获取输入流,进而操作,即可处理请求信息    entity2.getInputStream();        EntityUtils.consume(entity2);} finally {    response2.close();}

// httpclient流式 API

// getRequest.Get("http://targethost/homepage")    .execute().returnContent();// postRequest.Post("http://targethost/login")    .bodyForm(Form.form().add("username",  "vip").add("password",  "secret").build())    .execute().returnContent();

end

原创粉丝点击