请求外部接口的两种方式,get请求和post请求.

本文介绍了一种封装HTTP Get和Post请求的工具类,通过创建UrlTools类实现对外部接口的调用。Get请求通过读取输入流并转换为字符串返回,而Post请求则使用HttpClient发送JSON字符串,适用于处理第三方API调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Get请求

可以封装成工具类,代码如下,我这里工具类名叫UrlTools,方法名叫getStringByUrl(List urlList);参数传入一个list集合.集合中存放接口地址.

//get请求外部接口
public String getStringByUrl(List<String> urlList){

        for (int i = 0; i < urlList.size(); i++) {
            InputStream in = null;
            InputStreamReader isr = null;
            BufferedReader br = null;
            try {
                URL url = new URL(urlList.get(i));

                URLConnection conn = url.openConnection();
                conn.setConnectTimeout(10000);
                conn.setReadTimeout(10000);
                in = conn.getInputStream();
                isr = new InputStreamReader(in);
                br = new BufferedReader(isr);
                String line = "";
                StringBuilder content = new StringBuilder();
                while ((line = br.readLine()) != null) {
                    content.append(line);
                }
				/*logger.info(" 接口访问成功 - " + urlList.get(i));
				logger.info("content的结果: "+content.toString());*/
                return content.toString().trim();
            } catch (Exception e) {
                logger.error(" ** 接口访问失败 - "+urlList.get(i) +"\r\n 错误信息:" + e.getClass()+" - "+e.getMessage());
            } finally {
                if (null != br) {
                    try {
                        br.close();
                    } catch (IOException e) {
                    }
                }

                if (null != isr) {
                    try {
                        isr.close();
                    } catch (IOException e) {
                    }
                }

                if (null != in) {
                    try {
                        in.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
        return null;
    }

2.get请求使用方法
ArrayList<String> schooldetatils = new ArrayList<>();
schooldetatils.add("https://xcx.wanxue.cn/hwkycp/public/api/getSchoolDetail?code="+code);
String stringByUrl = UrlTools.INSTANCE.getStringByUrl(schooldetatils);
JSONObject stringByUrlObj = JSONObject.parseObject(stringByUrl);

在这里插入图片描述
把第三方接口存到一个list集合里,调用工具类UrlTools中的方法时,传入接口地址,因为我这里返回的数据格式是json,所以转成了json格式进行处理,使用开发工具IDEA的debug功能,打断点可以看到接口中返回的数据.

3.发送post请求

代码如下:

private static String sendPostJsonStr(String url, String jsonString) throws IOException {
        String resp = "";
        StringEntity entityStr = new StringEntity(jsonString,
                ContentType.create("text/plain", "UTF-8"));
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entityStr);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            resp = EntityUtils.toString(entity, "UTF-8");
            EntityUtils.consume(entity);
        } catch (ClientProtocolException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }
        }
        if (resp == null || resp.equals("")) {
            return "";
        }
        return resp;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值