对接第三方接口--使用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;}
    ...... 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

Java对象

public class B{
    private String id;
    private String ip;
    private String port;
    ......
    ...... 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

发送请求

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();
            }
        }
    }
}

原文地址:https://blog.csdn.net/zqhfsf/article/details/74353287

猜你喜欢

转载自blog.csdn.net/ywb201314/article/details/82884043