远程调用第三方接口

在实际的项目开发中,经常需要调用远程接口,下面给出一个例子

public static String doPost(String urlStr,String json,String charset) {
        String result = null;
        System.out.println("请求参数:"+json);
        try {
            //获取目标地址
            URL url = new URL(urlStr);
            //创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //设置向HttpURLConnection输出、输入(发送数据、接收数据),当请求为post时必须设置这两个参数
            connection.setDoOutput(true);
            connection.setDoInput(true);
            //设置请求方式
            connection.setRequestMethod("POST");
            //设置是否开启缓存,post请求时,缓存必须关掉
            connection.setUseCaches(false);

            //设置连接是否自动处理重定向(setFollowRedirects:所用http连接;setInstanceFollowRedirects:本次连接)
            connection.setInstanceFollowRedirects(true);
            //设置提交内容类型
            connection.setRequestProperty("Content-Type","application/json");
            connection.setRequestProperty("Host","172.16.24.63:8000");
            connection.setRequestProperty("Cookie", "=");
            connection.setRequestProperty("X-CSRF-TOKEN", "2572fgtdrged");
            //开始连接
            connection.connect();
            //发送请求
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(json.getBytes(charset));
            out.flush();
            out.close();
            //读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), charset));
            String lines;
            StringBuffer sb = new StringBuffer("");
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes());
                sb.append(lines);
            }
            result = sb.toString();
            System.out.println("请求返回结果:"+result);
            reader.close();
            // 断开连接
            connection.disconnect();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

引用:https://blog.csdn.net/qq_45171942/article/details/105450631

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

拉霍拉卡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值