对接第三方接口--使用post请求发送json数据

对接第三方接口–使用post请求发送json数据

实习4个多月,终于转正!终于可以安心好好上班,好好学习!第一篇播客记录下工作中的中的小知识点。

本文记录的内容如下:

  • 1.使用HttpClient相关类,包括PostMethod,RequestEntity,StringRequestEntity等

  • 2.实现用post请求方式发送json数据


第三方接口字段构建成model

将第三方提供的接口文档字段构建成model。

public class A{
    private String sn;
    private String host;
    private String port;
    ......

    public String getHost() {return host;}
    public void setHost(String host) {this.host = host;}
    ...... 
}

Java对象

public class B{
    private String id;
    private String ip;
    private String port;
    ......
    ...... 
}

发送请求

public class APITest {
    //这里是日志
    private static ....

    /**
     * api_url 请求路径 ,换成自己的路径
     */
    private String apiUrl = MapCache.getConfigVal("api_url");

    /**
     * http客户端
     */
    private HttpClient client = new HttpClient();

    /**
     * 将告警信息发送到百信API
     *
     * @param notice
     */
    public void sendNotice(B b) {

        //java对象封装成第三方类
        if (b != null) {
            A a = new A();
            a.setHost(b.getIp);
            ...
            send(a);
        }
    }

    /**
     * post请求发送json格式的数据至API
     *
     * @param A
     */
    public void send(A a) {
        if (this.apiUrl == null) {
            this.apiUrl = "http://xxx...";
        }

        if (this.apiUrl != null) {
            PostMethod postMethod = new PostMethod(this.apiUrl);
            Gson gson = new Gson();
            String data = gson.toJson(a);

            try {
                RequestEntity requestEntity = new StringRequestEntity(data.toString(), "application/json", "utf-8");
                postMethod.setRequestEntity(requestEntity);
            } catch (UnsupportedEncodingException e) {
                log.error("Java Object To JSON Error: ", e);
            }

            try {
                int httpCode = client.executeMethod(postMethod);
                if (httpCode == 200) {
                    sendInfoLog.info("发送到api成功:" + data.toString());
                } else {
                    sendInfoLog.info("发送到api失败:" + data.toString());
                }
            } catch (IOException e) {
                this.log.error("发送api post请求失败:", e);
            } finally {
                postMethod.releaseConnection();
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值