1. 程式人生 > >對接第三方介面--使用post請求傳送json資料

對接第三方介面--使用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();
            }
        }
    }
}