HttpClient学习笔记

HttpClient官方的一段概要

The Hyper-Text Transfer Protocol (HTTP) is perhaps the most significant protocol used on the Internet today. Web services, network-enabled appliances and the growth of network computing continue to expand the role of the HTTP protocol beyond user-driven web browsers, while increasing the number of applications that require HTTP support.
Although the java.net package provides basic functionality for accessing resources via HTTP, it doesn’t provide the full flexibility or functionality needed by many applications. HttpClient seeks to fill this void by providing an efficient, up-to-date, and feature-rich package implementing the client side of the most recent HTTP standards and recommendations.
Designed for extension while providing robust support for the base HTTP protocol, HttpClient may be of interest to anyone building HTTP-aware client applications such as web browsers, web service clients, or systems that leverage or extend the HTTP protocol for distributed communication.

超文本传输协议(HTTP)可能是当今互联网上使用的最重要的协议。Web服务、网络使能设备和网络计算的增长继续扩大HTTP协议在用户驱动的Web浏览器之外的作用,同时增加了需要HTTP支持的应用程序的数量。 虽然Java.NET包提供了通过HTTP访问资源的基本功能,但它不能提供许多应用程序所需的完全灵活性或功能性。HTTPClient通过提供最新的HTTP标准和建议的客户端来提供一个高效、最新、功能丰富的包来填补这一空白。
设计用于扩展,同时为基础HTTP协议提供强大的支持,HTTPClient可能会对任何构建HTTP感知客户端应用程序的人感兴趣,例如Web浏览器、Web服务客户端或利用或扩展HTTP协议进行分布式通信的系统。
Maven使用HttpClient需要依赖一个坐标

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5.5</version>
</dependency>

参考apache官方网站

用HttpClient实现get请求
    //创建一个可关闭的htttpClient对象
    CloseableHttpClient httpClient=HttpClients.createDefault();
    //创建一个GET对象
    HttpGet get=new HttpGet("http://hc.apache.org/");
    //执行请求
    CloseableHttpResponse  response = httpClient.execute(get);
    //获取状态码
    int statusCode=response.getStatusLine().getStatusCode();
    System.out.println(statusCode);//正常:200
    //关闭httpclient

    httpClient.close();
用HttpClient实现带参数的Get请求
    //创建一个httpclient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    //创建一个URI对象
    URIBuilder uriBuilder = new URIBuilder("https://www.baidu.com/");
    uriBuilder.addParameter("query", "花千骨");
    HttpGet get = new HttpGet(uriBuilder.build());
    //执行请求
    CloseableHttpResponse response = httpClient.execute(get);
    //获取状态码
    int statusCode = response.getStatusLine().getStatusCode();
    System.out.println(statusCode);//正常:200
    //获取响应给客户端的实体信息
    HttpEntity entity = response.getEntity();
    String string = EntityUtils.toString(entity, "utf-8");
    System.out.println(string);//输出
    //关闭httpclient
    response.close();
    httpClient.close();
用HttpClient实现post请求
    //创建一个可关闭的htttpClient对象
    CloseableHttpClient httpClient=HttpClients.createDefault();
    //创建一个post对象
    HttpPost post = new HttpPost("http://localhost:8080/login.do");
    //执行post请求
    CloseableHttpResponse response = httpClient.execute(post);
    //获取状态码
    int statusCode=response.getStatusLine().getStatusCode();
    System.out.println(statusCode);//正常:200
    //关闭httpclient
    httpClient.close();
用HttpClient实现带参数的post请求
    //创建一个可关闭的htttpClient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();

    //创建一个post对象
    HttpPost post = new HttpPost("http://localhost:8080/login.do");
    //创建一个Entity。模拟一个表单
    List<NameValuePair> kvList = new ArrayList<>();
    kvList.add(new BasicNameValuePair("username", "zhangsan"));
    kvList.add(new BasicNameValuePair("password", "123"));

    //包装成一个Entity对象
    StringEntity entity = new UrlEncodedFormEntity(kvList, "utf-8");
    //设置请求的内容
    post.setEntity(entity);

    //执行post请求
    CloseableHttpResponse response = httpClient.execute(post);
    String string = EntityUtils.toString(response.getEntity());
    System.out.println(string);
    response.close();
    httpClient.close();

若其它项目也使用的话可以封装成一个工具类。

 // HTTP POST请求
    public static String sendPost(String url,JSONObject json) throws Exception {


        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);



        StringEntity s = new StringEntity(json.toString(),"UTF-8");
        s.setContentEncoding("UTF-8");
        s.setContentType("application/json");
        post.setEntity(s);
        HttpResponse response = client.execute(post);
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + post.getEntity());
        System.out.println("Response Code : " +
                                    response.getStatusLine().getStatusCode());

        BufferedReader rd = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent(),"UTF-8"));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        return result.toString();
    }

    // HTTP GET请求
    public static String sendGet() throws Exception {

        String url = "http://www.google.com/search?q=developer";

        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet request = new HttpGet(url);


        HttpResponse response = client.execute(request);

        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " +
                       response.getStatusLine().getStatusCode());

        BufferedReader rd = new BufferedReader(
                       new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        System.out.println(result.toString());
        return result.toString();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值