java代码实现HttpClient请求

一、HttpClient简介

在这里插入图片描述

二、HttpClient应用

1.发送get请求不带参数

(1)创建springBoot项目。
(2)添加HttpClient依赖。

<!--        Httpclient依赖-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.5</version>
        </dependency>

(3)controlelr层

@RestController
public class HttpClientController {
    
    
    @Autowired
    HttpClientService httpClientService;

//    get无参请求
    @RequestMapping("/sentGet")
    public void  sentGet() throws IOException {
    
    
        httpClientService.sentGet();
    }
}

(4)service层

@Service
@Slf4j
public class HttpClientService {
    
    
//    发送get无参请求
    public void sentGet() throws IOException {
    
    
//        创建一个常见的HttpClient对象,使用的是HttpClients工具类创建
        CloseableHttpClient client = HttpClients.createDefault();
//        创建get请求对象
        String url="http://www.baidu.com";
        HttpGet httpGet=new HttpGet(url);
//        发送请求,并返回响应
        CloseableHttpResponse execute = client.execute(httpGet);
//        处理响应
//        获取响应的状态码
        int code = execute.getStatusLine().getStatusCode();
//        获取响应的内容,它把响应的内容封装到了HttpEntity对象中了
//        通过getEntity()获取
        HttpEntity entity = execute.getEntity();
//        然后可以使用EntityUtils工具类来获取,它有两个参数,第二个是编码格式
        String content = EntityUtils.toString(entity, "utf-8");
        log.info("响应的内容为:"+content);
        System.out.println(content);
//        关闭连接
        client.close();
    }
}

2.发送get请求带参数

//    get请求带参数
    public void sentGet2() throws Exception {
    
    
//        创建一个常见的HttpClient对象,使用的是HttpClients工具类创建
        CloseableHttpClient client = HttpClients.createDefault();
//        创建一个封装uri的对象
        String url="https://cn.bing.com/search";
        URIBuilder uriBuilder=new URIBuilder(url);
//        设置请求参数
        uriBuilder.addParameter("q","你好李焕英");
//        创建一个gat请求对象
        HttpGet httpGet=new HttpGet(uriBuilder.build());
//        发送请求,返回响应对象
        CloseableHttpResponse execute = client.execute(httpGet);
//        获取响应状态码
        int code = execute.getStatusLine().getStatusCode();
//        获取响应内容
//        通过getEntity()获取
        HttpEntity entity = execute.getEntity();
//        然后可以使用EntityUtils工具类来获取,它有两个参数,第二个是编码格式
        String content = EntityUtils.toString(entity, "utf-8");
        System.out.println("状态码为:"+code);
        System.out.println("响应的内容为:"+content);
//        关闭连接
        client.close();
    }
}

3.发送post请求不带参数

(1)再去创建一个postController类

@RestController
public class PostController {
    
    

//    发送的post请求到这里,不带参数
    @PostMapping ("/posts")
    public Object posts(){
    
    
//        创建一个Map
        Map<String,String> map=new HashMap<>();
        map.put("msg","OK");
        return map;

    }
}

(2)然后在HttpClientController类中写发送post请求

//    post请求
    @RequestMapping("/sentPost")
    public void  sentPost() throws Exception {
    
    
    //        不带参数
            httpClientService.sentPost();
    //        带参数
//        httpClientService.sentGet2();
    }

(3)service层

//    发送post请求,不带参数
    public void sentPost() throws Exception {
    
    
//        创建HttpClient对象
        CloseableHttpClient client = HttpClients.createDefault();
//        创建post请求对象
        String url="http://localhost:8080/posts";
        HttpPost httpPost=new HttpPost(url);
//        发送请求
        CloseableHttpResponse execute = client.execute(httpPost);

//        处理响应响应对象
//       获取响应状态码
        int code = execute.getStatusLine().getStatusCode();
//        获取响应内容
        HttpEntity entity = execute.getEntity();
        String content = EntityUtils.toString(entity, "utf-8");
        System.out.println("状态码为:"+code);
        System.out.println("响应内容为:"+content);
//        关闭连接
        client.close();
    }

4.发送post请求带参数

user实体类

import lombok.Data;

@Data
public class User {
    
    
    private String name;
    private String pwd;
}

(1)对于postController类

//    接收post请求带参数
    @PostMapping ("/postParam")
    public Object postParam(User user){
    
    
    //        创建一个Map
        Map<String,String> map=new HashMap<>();
        map.put("name",user.getName());
        map.put("pwd",user.getPwd());
        return map;
    }

(2)对于HttpClientController类

//    post请求
    @RequestMapping("/sentPost")
    public void  sentPost() throws Exception {
    
    
    //        不带参数
//            httpClientService.sentPost();
    //        带参数
        httpClientService.sentPostParam();
    }

(3)对于service层

//    发送post请求带参数
    public void sentPostParam() throws Exception {
    
    
//        创建HttpClient对象
        CloseableHttpClient client = HttpClients.createDefault();
//        创建post请求对象
        String url="http://localhost:8080/postParam";
        HttpPost httpPost=new HttpPost(url);
//        给定参数
        List<BasicNameValuePair> list=new ArrayList<>();
        list.add(new BasicNameValuePair("name","万叶"));
        list.add(new BasicNameValuePair("pwd","123"));
//        将参数做字符串转换
        StringEntity stringEntity=new UrlEncodedFormEntity(list,"utf-8");
//        向post请求中绑定参数
        httpPost.setEntity(stringEntity);

//        发送请求,返回响对象
        CloseableHttpResponse execute = client.execute(httpPost);
//        处理响应
//        获取状态码
        int code = execute.getStatusLine().getStatusCode();
//        获取响应内容
        HttpEntity entity = execute.getEntity();
        String content = EntityUtils.toString(entity, "utf-8");
        System.out.println("状态码为:"+code);
        System.out.println("响应内容为:"+content);
//        关闭连接
        client.close();
    }

5.post请求带json格式的数据

(1)对于postController类

    //    接收post请求Json格式的参数
    @PostMapping ("/postParamJson")
    public Object postParamJson(@RequestBody User user){
    
    
        //        创建一个Map
        Map<String,String> map=new HashMap<>();
        map.put("name",user.getName());
        map.put("pwd",user.getPwd());
        return map;
    }

(2)对于HttpClientController类

//    post请求
    @RequestMapping("/sentPost")
    public void  sentPost() throws Exception {
    
    
    //        不带参数
//            httpClientService.sentPost();
    //        带参数
//        httpClientService.sentPostParam();
//        发送json格式的参数
        httpClientService.sentPostParamJson();

    }

对于service层

//    发送json格式的参数
    public void sentPostParamJson() throws Exception {
    
    
//        创建HttpClient对象
        CloseableHttpClient client = HttpClients.createDefault();
//        创建HttpPost对象
        String url="http://localhost:8080/postParamJson";
        HttpPost httpPost=new HttpPost(url);
//        创建一个json字符串
        User user=new User();
        user.setName("可莉");
        user.setPwd("456");

        //Java对象转化为JSON对象
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(user);
//        json对象转为string字符串
        String json = jsonObject.toString();
//        设置请求体,第二个参数是json格式
        StringEntity stringEntity=new StringEntity(json, ContentType.APPLICATION_JSON);
//        向请求体中绑定参数
        httpPost.setEntity(stringEntity);

//        发送请求,返回响应对象
        CloseableHttpResponse execute = client.execute(httpPost);
//        获取状态码
        int code = execute.getStatusLine().getStatusCode();
//        获取响应内容
        HttpEntity entity = execute.getEntity();
        String content = EntityUtils.toString(entity, "utf-8");
        //10.String转java对象
        User user1= JSON.parseObject(content,User.class);

        System.out.println("状态码为:"+code);
        System.out.println("响应内容为:"+content);
        System.out.println("Json转为User对象为:"+user1);
//        关闭连接
        client.close();
    }

6.HttpClient自定义工具类使用

当我们在使用httpClient去发送get或者post请求的时候,都需要去写建立连接,关闭连接操作,这时候我们就可以自己去写一个httpClient工具类实现。

7.获取HttpClient请求头中的信息

(1)对于service层

//    发送post请求通过json方式,其中设置请求头信息
    public void sentPostParamJsonTop() throws Exception {
    
    
    //        创建HttpClient对象
        CloseableHttpClient client = HttpClients.createDefault();
    //        创建HttpPost对象
        String url="http://localhost:8080/postParamJson";
        HttpPost httpPost=new HttpPost(url);
    //        创建一个json字符串
        User user=new User();
        user.setName("可莉");
        user.setPwd("456");

        //Java对象转化为JSON对象
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(user);
    //        json对象转为string字符串
        String json = jsonObject.toString();
    //        设置请求体,第二个参数是json格式
        StringEntity stringEntity=new StringEntity(json, ContentType.APPLICATION_JSON);
    //        向请求体中绑定参数
        httpPost.setEntity(stringEntity);
//        设置请求头信息
        // 设置请求头
        httpPost.addHeader("content-type", "application/json;chartset=UTF-8");
        httpPost.addHeader("X-USER-AUTH","USERID=123456");

        // 请求连接配置
        RequestConfig config = RequestConfig.custom()
                // 连接请求超时ms
                .setConnectTimeout(1000)
                // 连接超时时间ms
                .setConnectionRequestTimeout(1000)
                // 读取超时ms
                .setSocketTimeout(10 * 1000).build();

        // 设置连接配置
        httpPost.setConfig(config);


    //        发送请求,返回响应对象
        CloseableHttpResponse execute = client.execute(httpPost);

    //        获取状态码
        int code = execute.getStatusLine().getStatusCode();
    //        获取响应内容
        HttpEntity entity = execute.getEntity();
        String content = EntityUtils.toString(entity, "utf-8");
        //10.String转java对象
        User user1= JSON.parseObject(content,User.class);

        // 获取httpClient响应的请求头header
        Header responseHeader = execute.getFirstHeader("content-type");
        HeaderElement[] responseHeaderElements = responseHeader.getElements();
        String value = responseHeaderElements[0].toString();


        System.out.println("状态码为:"+code);
        System.out.println("响应内容为:"+content);
        System.out.println("Json转为User对象为:"+user1);
        System.out.println("获取请求头信息为:"+value);
    //        关闭连接
        client.close();
    }

猜你喜欢

转载自blog.csdn.net/m0_44980168/article/details/130040691
今日推荐