HttpClient / Http客户端

HttpClient / Http客户端:

    • HttpClient的定义
    • HttpClient的作用
    • HttpClient的常用核心API
    • HttpClient要导入的依赖
    • HttpClient发送请求的步骤
    • HttpClient入门案例:
      • HttpClient(Http客户端)发送get请求
      • HttpClient(Http客户端)发送post请求
    • HttpClient工具类 (代码)

HttpClient的定义

  • HttpClient (Http客户端) 是Apache Jakarta Common 下的子项目,可以用来提供高效率最新的功能丰富的支持HTTP协议客户端编程工具包,其支持HTTP协议最新的版本和建议。
  • 说的直白点就是
    我们可在 java 程序中可通过HttpClient(Http客户端) 这个工具包构造http请求发送http请求接收响应结果解析(请求)返回的结果
    (在Java中通过编码的方式来发送http请求

HttpClient的作用

  • 可在 java程序中可通过HttpClient(Http客户端) 这个工具包构造http请求发送http请求接收响应结果解析(请求)返回的结果

HttpClient的常用核心API

  • HttpClient
  • HttpClients
  • CloseableHttpClient
  • HttpGet
  • HttpPost

HttpClient要导入的依赖

<dependency>
   <groupId>org.apache.httpcomponentsgroupId>
   <artifactId>httpclientartifactId>
   <version>4.5.13version>
dependency>

HttpClient发送请求的步骤

  • 第一步创建HttpClient对象 (Http客户端对象)。使用该对象可进行“发送请求”。
    HttpClient (Http客户端类)是一个接口,最后创建是其的实现类

  • 第二步创建http请求对象。比如说我们要发送一个get请求,我们就要创建一个HttpGet对象;如果要发送post请求,我们就就要构建一个HttpPost对象。

  • 第三步发送请求,接收响应结果。调用HttpClient对象execute方法发送请求(发送请求),且接收响应结果

  • 第四步、解析返回结果

    • 获取服务端返回状态码
    • 获取客户端返回的数据 (获得响应体,且解析响应体)。
  • 第五步关闭资源

    (ps : 例子在下面的入门案例中。)

HttpClient入门案例:

HttpClient(Http客户端)发送get请求

@SpringBootTest
public class HttpClientTest {  //Http客户端测试类

    /**
      测试通过httpclient(Http客户端)发送GET请求
     */
    @Test
    public void testGet() throws Exception {
        
       //创建HttpClient对象 --HttpClien为接口,最后创建出来的为: 与其相关的实现类
        CloseableHttpClient httpClient = HttpClients.createDefault();

       //创建Http请求对象 (get请求)
        HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status");

        //发送请求,接收响应结果
        CloseableHttpResponse response = httpClient.execute(httpGet);

        //解析返回结果
        //获取服务端返回的状态码
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println("服务端返回的状态码为: " +statusCode);
        //获取服务端(响应)返回的数据 --- 获得响应体
        HttpEntity entity = response.getEntity();
        //通过EntityUtils工具类解析“响应体” --- 解析响应体
        String body = EntityUtils.toString(entity);
        System.out.println("服务端返回的数据为: "+body);

        //关闭资源
        response.close();
        httpClient.close();
    }
}

HttpClient(Http客户端)发送post请求

@SpringBootTest
public class HttpClientTest {  //Http客户端测试类

    /**
     * 测试类通过HttpClient(Http客户端)发送Post请求
     */
    @Test
    public void testPost() throws Exception {
        //创建HttpClient对象 --- HttpClient为接口,最后创建出来的为: 与其相关的实现类。
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //创建Http请求对象 (Post请求)
     HttpPost httpPost = new HttpPost("http://localhost:8080/admin/employee/login");
        //设置post请求的参数 (设置Http请求对象的“参数”)
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", "admin");
        jsonObject.put("password", 123456);
     StringEntity entity = new StringEntity(jsonObject.toString()); //参数为:json字符串
        entity.setContentEncoding("utf-8");  //设置请求的“编码方式”
        //请求提交过来的是json格式的数据,这样后端才能正确解析数据
        entity.setContentType("application/json"); //设置请求的“数据格式”
        //设置post请求的参数
        httpPost.setEntity(entity);

        //发送请求,接收响应结果
        CloseableHttpResponse reponse = httpClient.execute(httpPost);

        //解析返回结果
     int statusCode = reponse.getStatusLine().getStatusCode();   //获取服务端返回的状态码
        System.out.println("响应码为: "+statusCode);
        HttpEntity entity1 = reponse.getEntity();
        String body = EntityUtils.toString(entity1); //使用EntityUtils解析响应体
        System.out.println("响应数据为: "+body);

        //关闭资源
        reponse.close();
        httpClient.close();
    }
}

HttpClient工具类 (代码)

package com.sky.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Http工具类
 */
public class HttpClientUtil {

    static final  int TIMEOUT_MSEC = 5 * 1000;

    /**
     * 发送GET方式请求
     * @param url
     * @param paramMap
     * @return
     */
    public static String doGet(String url,Map<String,String> paramMap){
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        String result = "";
        CloseableHttpResponse response = null;

        try{
            URIBuilder builder = new URIBuilder(url);
            if(paramMap != null){
                for (String key : paramMap.keySet()) {
                    builder.addParameter(key,paramMap.get(key));
                }
            }
            URI uri = builder.build();

            //创建GET请求
            HttpGet httpGet = new HttpGet(uri);

            //发送请求
            response = httpClient.execute(httpGet);

            //判断响应状态
            if(response.getStatusLine().getStatusCode() == 200){
                result = EntityUtils.toString(response.getEntity(),"UTF-8");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                response.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    /**
     * 发送POST方式请求
     * @param url
     * @param paramMap
     * @return
     * @throws IOException
     */
    public static String doPost(String url, Map<String, String> paramMap) throws IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";

        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);

            // 创建参数列表
            if (paramMap != null) {
                List<NameValuePair> paramList = new ArrayList();
                for (Map.Entry<String, String> param : paramMap.entrySet()) {
        paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }

            httpPost.setConfig(builderRequestConfig());

            // 执行http请求
            response = httpClient.execute(httpPost);

            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    /**
     * 发送POST方式请求
     * @param url
     * @param paramMap
     * @return
     * @throws IOException
     */
    public static String doPost4Json(String url, Map<String, String> paramMap) throws IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";

        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);

            if (paramMap != null) {
                //构造json格式数据
                JSONObject jsonObject = new JSONObject();
                for (Map.Entry<String, String> param : paramMap.entrySet()) {
                    jsonObject.put(param.getKey(),param.getValue());
                }
        StringEntity entity = new StringEntity(jsonObject.toString(),"utf-8");
                //设置请求编码
                entity.setContentEncoding("utf-8");
                //设置数据类型
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }

            httpPost.setConfig(builderRequestConfig());

            // 执行http请求
            response = httpClient.execute(httpPost);

            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }
    private static RequestConfig builderRequestConfig() {
        return RequestConfig.custom()
                .setConnectTimeout(TIMEOUT_MSEC)
                .setConnectionRequestTimeout(TIMEOUT_MSEC)
                .setSocketTimeout(TIMEOUT_MSEC).build();
    }
}

你可能感兴趣的:(Java知识点-整合,http,网络协议,网络)