Java调用Restful接口

本文介绍了一种使用Java实现的HTTP客户端工具类,包括通过HttpClient和HttpURLConnection发送POST请求的方法。示例代码展示了如何设置请求参数及处理响应,适用于快速集成后端RESTful API。

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

依赖jar

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.70</version>
        </dependency>

工具类

一:
public static String HttpPostToJson(String url, String params) {
        //获取默认的client实例
        CloseableHttpClient client = HttpClients.createDefault();
        //创建httppost实例
        HttpPost httpPost = new HttpPost(url);
        //添加请求头
        httpPost.addHeader("Content-type", "application/json;charset=utf-8");
        String result = "";
        try {
            httpPost.setEntity(new StringEntity(params, "utf-8"));
            CloseableHttpResponse resp = client.execute(httpPost);

            try {
                int statusCode = resp.getStatusLine().getStatusCode();
                if (statusCode == HttpStatus.SC_OK) {
                    HttpEntity entity = resp.getEntity();
                    result = EntityUtils.toString(entity, "UTF-8");
                } else {
                    throw new RuntimeException("http请求返回状态码值不为200,返回状态码为:" + statusCode);
                }
            } finally {
                resp.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }
二:
public static String doPost(String HttpUrl, String Param) {
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        StringBuffer sbf = new StringBuffer();
        HashMap hashMap = new HashMap();
        try {
            URL url = new URL(HttpUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(15000);
            connection.setReadTimeout(6000);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-type", "application/json");
            os = connection.getOutputStream();
            os.write(Param.getBytes());
            int responseCode = connection.getResponseCode();//响应成功==200
            is = connection.getInputStream();
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String temp;
            String StringResoultMap = null;
            labe9527:
            if (responseCode != 200) {
                break labe9527;
            } else {
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                }
                StringResoultMap = String.valueOf(sbf);
            }
            if (null != StringResoultMap) {
                hashMap = JSON.parseObject(StringResoultMap, HashMap.class);
            }
        } catch (Exception e) {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException ex) {
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException ex) {
                }
            }
            if(is != null) {
                try {
                    is.close();
                } catch (IOException ex) {
                }
            }
            connection.disconnect();
        }finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException ex) {
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException ex) {
                }
            }
            if(is != null) {
                try {
                    is.close();
                } catch (IOException ex) {
                }
            }
            connection.disconnect();
        }
        //返回报文
        /*{"reply":{
            "returnCode":{
                "type":"S",
                "code":"AAAAAA",
                "domain":null
            }
        }}*/
        Map<String,Object> resReplyMap = MapUtils.getMap(hashMap,"reply");
        Map<String,Object> resReplyReturnCodeMap = MapUtils.getMap(resReplyMap,"returnCode");
        String type = MapUtils.getString(resReplyReturnCodeMap,"type");
        String code = MapUtils.getString(resReplyReturnCodeMap,"code");
        if(!"S".equals(type) && !"AAAAAA".equals(code)){
            return "false";
        }else{
            return "success";
        }
    }

后端Restful接口的调用:
1.HttpURLConnection实现
    2.HttpClient实现
    3.Spring的RestTemplate
可参考:https://blog.youkuaiyun.com/qq_34155601/article/details/70236948

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值