HttpClient的API

HttpClient

用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包–>工具API

举个栗子

package com.jt.test;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;

import java.io.IOException;

/**
 * @author Osiris
 * @date 2020/12/10 20:18
 */
public class TestHttpClient {
    /**
     * 实例化HttpClient对象
     * 定义远程访问的url地址
     * 定义请求类型的对象
     * 发起http请求,获得响应结果
     * 对返回结果进行校验,获取真实数据信息
     */
    @Test
    public void testGet() throws IOException {
        HttpClient httpClient=HttpClients.createDefault();
        String url="http://www.baidu.com";
        HttpGet httpGet=new HttpGet(url);
        HttpResponse httpResponse=httpClient.execute(httpGet);
        //获取状态码
        int status=httpResponse.getStatusLine().getStatusCode();
        if(status==200){
            //获取响应结果
            HttpEntity entity=httpResponse.getEntity();
            String result= EntityUtils.toString(entity,"UTF-8");
            System.out.println(result);
        }
    }
}
@RequestMapping("testHttpClient")
    @ResponseBody
    public List<User> testHttpClient(){
        return userService.testHttpClient();
    }
public interface UserService {
    List<User> testHttpClient();
}
@Override
    public List<User> testHttpClient() {
        /**
         * 由jt-web服务器连接jt-sso的服务器
         */
        List<User> userList=new ArrayList<>();
        //List<User> userList2=new ArrayList<>();
        String url="http://sso.jt.com/user/testHttpClient";
        HttpClient httpClient=HttpClients.createDefault();
        HttpGet httpGet=new HttpGet(url);
        try {
            HttpResponse httpResponse=httpClient.execute(httpGet);
            if(httpResponse.getStatusLine().getStatusCode()==200){
                HttpEntity httpEntity=httpResponse.getEntity();
                String result= EntityUtils.toString(httpEntity,"UTF-8");
                userList=ObjectMapperUtil.toObj(result,userList.getClass());
                /*for(LinkedHashMap<String,Object> map:userList){
                    User uerTemp=new User();
                    uerTemp.setId(Long.parseLong(map.get("id")+""));
                }*/
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return userList;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值