Java:HttpClient访问第三方带参接口

文章介绍了如何使用HTTPClient库在Java中执行GET和POST请求来调用第三方接口。对于GET请求,它处理了路径参数的拼接和非拼接情况;对于POST请求,数据以JSON格式发送。在每个请求中,都设置了Content-Type头,并检查了响应状态码以确保请求成功。
摘要由CSDN通过智能技术生成

httpclient访问第三方接口分为访问Post请求和访问Get请求.

话不多说,先放get请求访问方法:

data是接口入参,url是接口路径.

public static JSONArray doGet(JSONObject data, String url) {
            CloseableHttpClient client = HttpClients.createDefault();
            JSONArray jsonObject = null;
            String param = null;
            List<NameValuePair> list = new ArrayList<>();            //该list为传递给httpClient的参数
            //这里加了一个判断,支持字符串拼接的路径
            if (url.endsWith("}")) {
                Map<String,Object> map = data.toJavaObject(Map.class);
                Set set = map.keySet();
                int i = 0;
                Object[] array = new Object[set.size()];
                for (Object key : set) {
                    array[i++] = map.get(key);
                }
                param = Arrays.stream(array).map(n -> String.valueOf(n)).collect(Collectors.joining("/"));
            //路径非拼接时
            }else {
                Map map = data.toJavaObject(Map.class);
                map.forEach((key,value) -> {
                    if (value != null){
                        //键值对类型
                        BasicNameValuePair basicNameValuePair = new BasicNameValuePair(key.toString(),value.toString());
                        list.add(basicNameValuePair);
                    }
                });
            }
            try {
                //防止字符乱码
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list,"UTF-8");
                String params = EntityUtils.toString(urlEncodedFormEntity);
                // 要调用的接口方法
                HttpGet get = null;
                //判断url是拼接
                if (url.endsWith("}")) {
                    get = new HttpGet(url.substring(0,url.indexOf("{"))+"/"+param);
                }else {//不是拼接
                    get = new HttpGet(url+"?"+params);
                }
                //设置请求头
                get.addHeader("content-type", "application/json");
                //token
//                get.addHeader("Authorization","");
                HttpResponse res = client.execute(get);
                String response = EntityUtils.toString(res.getEntity());
                System.out.println(response);
                System.out.println(res.getStatusLine().getStatusCode());
                if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    //这里是JSONObject还是JSONArray根据返回结果定
                    jsonObject = JSONObject.parseArray(response);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return jsonObject;
        }

post请求:

public static JSONObject doPost(JSONObject data, String url) {
        CloseableHttpClient client = HttpClients.createDefault();
        JSONObject jsonObject = null;
        //这里加了一个判断,支持字符串拼接的路径
        String param = null;
        if (url.endsWith("}")) {
            Map<String,Object> map = data.toJavaObject(Map.class);
            Set set = map.keySet();
            int i = 0;
            Object[] array = new Object[set.size()];
            for (Object key : set) {
                array[i++] = map.get(key);
            }
            param = Arrays.stream(array).map(n -> String.valueOf(n)).collect(Collectors.joining("/"));
            //路径非拼接时
        }
        try {
            // 要调用的接口方法
            HttpPost post;
            //判断url是拼接
            if (url.endsWith("}")) {
                post = new HttpPost(url.substring(0,url.indexOf("{"))+"/"+param);
            }else {//不是拼接
                post = new HttpPost(url);
                post.setEntity(new StringEntity(data.toString(),"UTF-8"));
            }
            post.addHeader("content-type", "application/json");
            //post.addHeader("Authorization","Bearer "+ token);

            HttpResponse res = client.execute(post);
            String response = EntityUtils.toString(res.getEntity());
            System.out.println(response);
            System.out.println(res.getStatusLine().getStatusCode());
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                jsonObject = JSONObject.parseObject(response);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return jsonObject;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值