Java请求接口,解析接口返回的json数据并存到数据库中

需求:调用其他平台接口,根据json格式里的字段获取数据并存到数据库中。

/定义接收格式,可以根据需求增加和修改
@Data
public class ETest01 implements Serializable {

    /**
     * state : 1
     * message : OK
     * data : [{"}]
     */

    private int state;
    private String message;
    private List data;

    @Data
    public static class DataBean implements Serializable {
        /**
         * cameraIndexCode : 111
         * cameraName : 1
         * cameraTypeName : 2
         * channelNo : 3
         * encodeDevIndexCode : 4
         * gbIndexCode : 5
         * regionIndexCode : 6
         * updateTime : 2021-08-24T09:00:52.000+00:00
         * message : null
         */
        private String cameraIndexCode;
        private String cameraName;
        private String cameraTypeName;
        private int channelNo;
        private String encodeDevIndexCode;
        private String gbIndexCode;
        private String regionIndexCode;
        private String updateTime;
        private Object message;

    }
}

import com.google.gson.Gson;
import com.httprequest.demo.entity.ETest01;
import com.httprequest.demo.utils.JsonUtil;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.jupiter.api.Test;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.sql.;
import java.util.
;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

/**

  • HTTP请求
    */
    public class HTTPUtils {
    private static final int TIMEOUT = 45000;
    public static final String ENCODING = “UTF-8”;

    /**

    • 创建请求连接

    • url:地址

    • method:方法

    • headerParameters:请求头

    • body:请求内容
      */
      private static HttpURLConnection createConnection(String url,
      String method, Map headerParameters, String body)
      throws Exception {
      URL Url = new URL(url);
      trustAllHttpsCertificates();
      HttpURLConnection httpConnection = (HttpURLConnection) Url
      .openConnection();
      // 设置请求时间
      httpConnection.setConnectTimeout(TIMEOUT);
      // 设置 header
      if (headerParameters != null) {
      Iterator iteratorHeader = headerParameters.keySet()
      .iterator();
      while (iteratorHeader.hasNext()) {
      String key = iteratorHeader.next();
      httpConnection.setRequestProperty(key,
      headerParameters.get(key));
      }
      }
      httpConnection.setRequestProperty(“Content-Type”,
      “application/x-www-form-urlencoded;charset=” + ENCODING);
      // 设置请求方法
      httpConnection.setRequestMethod(method);
      httpConnection.setDoOutput(true);
      httpConnection.setDoInput(true);
      // 写query数据流
      if (!(body == null || body.trim().equals(""))) {
      OutputStream writer = httpConnection.getOutputStream();
      try {
      writer.write(body.getBytes(ENCODING));
      } finally {
      if (writer != null) {
      writer.flush();
      writer.close();
      }
      }
      }

      // 请求结果
      int responseCode = httpConnection.getResponseCode();
      if (responseCode != 200) {
      throw new Exception(responseCode
      + “:”
      + inputStream2String(httpConnection.getErrorStream(),
      ENCODING));
      }
      return httpConnection;
      }

    /**

    • POST请求

    • address:请求地址

    • headerParameters:请求头

    • body:请求内容
      */
      public static String post(String address,
      Map headerParameters, String body) throws Exception {

      return proxyHttpRequest(address, “POST”, null,
      getRequestBody(headerParameters));
      }

    /**

    • GET请求

    • address:请求地址

    • headerParameters:请求头

    • body:请求内容
      */
      public static String get(String address,
      Map headerParameters, String body) throws Exception {

      return proxyHttpRequest(address + “?”
      + getRequestBody(headerParameters), “GET”, null, null);
      }

    /**

    • 读取网络文件
    • address:地址
    • headerParameters:请求头
    • file:文件
      */
      public static String getFile(String address,
      Map headerParameters, File file) throws Exception {
      String result = “fail”;
      HttpURLConnection httpConnection = null;
      try {
      httpConnection = createConnection(address, “POST”, null,
      getRequestBody(headerParameters));
      result = readInputStream(httpConnection.getInputStream(), file);
      } catch (Exception e) {
      throw e;
      } finally {
      if (httpConnection != null) {
      httpConnection.disconnect();
      }
      }
      return result;
      }

    public static byte[] getFileByte(String address,
    Map headerParameters) throws Exception {
    byte[] result = null;
    HttpURLConnection httpConnection = null;
    try {
    httpConnection = createConnection(address, “POST”, null,
    getRequestBody(headerParameters));
    result = readInputStreamToByte(httpConnection.getInputStream());
    } catch (Exception e) {
    throw e;
    } finally {
    if (httpConnection != null) {
    httpConnection.disconnect();
    }
    }
    return result;
    }

    public static String readInputStream(InputStream in, File file)
    throws Exception {
    FileOutputStream out = null;
    ByteArrayOutputStream output = null;
    try {
    output = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len = 0;
    while ((len = in.read(buffer)) != -1) {
    output.write(buffer, 0, len);
    }
    out = new FileOutputStream(file);
    out.write(output.toByteArray());
    } catch (Exception e) {
    throw e;
    } finally {
    if (output != null) {
    output.close();
    }
    if (out != null) {
    out.close();
    }
    }
    return “success”;
    }

    public static byte[] readInputStreamToByte(InputStream in) throws Exception {
    FileOutputStream out = null;
    ByteArrayOutputStream output = null;
    byte[] byteFile = null;
    try {
    output = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len = 0;
    while ((len = in.read(buffer)) != -1) {
    output.write(buffer, 0, len);
    }
    byteFile = output.toByteArray();
    } catch (Exception e) {
    throw e;
    } finally {
    if (output != null) {
    output.close();
    }
    if (out != null) {
    out.close();
    }
    }

     return byteFile;
    

    }

    public static String proxyHttpRequest(String address, String method,
    Map headerParameters, String body) throws Exception {
    String result = null;
    HttpURLConnection httpConnection = null;
    try {
    httpConnection = createConnection(address, method, headerParameters, body);
    String encoding = “UTF-8”;
    if (httpConnection.getContentType() != null
    && httpConnection.getContentType().indexOf(“charset=”) >= 0) {
    encoding = httpConnection.getContentType().substring(httpConnection.getContentType().indexOf(“charset=”) + 8);
    }
    result = inputStream2String(httpConnection.getInputStream(), encoding);
    } catch (Exception e) {
    throw e;
    } finally {
    if (httpConnection != null) {
    httpConnection.disconnect();
    }
    }
    //返回结果2
    return result;
    }

    /**

    • 将参数化为 body
    • @param params
    • @return
      */
      public static String getRequestBody(Map params) {
      return getRequestBody(params, true);
      }

    /**

    • 将参数化为 body

    • @param params

    • @return
      */
      public static String getRequestBody(Map params,
      boolean urlEncode) {
      StringBuilder body = new StringBuilder();
      Iterator iteratorHeader = params.keySet().iterator();
      while (iteratorHeader.hasNext()) {
      String key = iteratorHeader.next();
      String value = params.get(key);
      if (urlEncode) {
      try {
      body.append(key + “=” + URLEncoder.encode(value, ENCODING)
      + “&”);
      } catch (UnsupportedEncodingException e) {

           }
       } else {
           body.append(key + "=" + value + "&");
       }
      

      }
      if (body.length() == 0) {
      return “”;
      }
      return body.substring(0, body.length() - 1);
      }

    private static String inputStream2String(InputStream input, String encoding)
    throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(input,
    encoding));
    StringBuilder result = new StringBuilder();
    //返回结果
    String temp = null;
    while ((temp = reader.readLine()) != null) {
    result.append(temp);
    }

     return result.toString();
    

    }

    private static void trustAllHttpsCertificates() throws Exception {
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
    public boolean verify(String str, SSLSession session) {
    return true;
    }
    });
    javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
    javax.net.ssl.TrustManager tm = new miTM();
    trustAllCerts[0] = tm;
    javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext
    .getInstance(“SSL”);
    sc.init(null, trustAllCerts, null);
    javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc
    .getSocketFactory());
    }

    //设置 https 请求证书
    static class miTM implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
    return null;
    }

     public boolean isServerTrusted(
             java.security.cert.X509Certificate[] certs) {
         return true;
     }
    
     public boolean isClientTrusted(
             java.security.cert.X509Certificate[] certs) {
         return true;
     }
    
     public void checkServerTrusted(
             java.security.cert.X509Certificate[] certs, String authType)
             throws java.security.cert.CertificateException {
         return;
     }
    
     public void checkClientTrusted(
             java.security.cert.X509Certificate[] certs, String authType)
             throws java.security.cert.CertificateException {
         return;
     }
    

    }

    @Test
    public void test01() throws Exception {
    //
    Gson gson = new Gson();
    String address = “http://localhost:8088/testWeb/testjson”;
    String res = get(address, new HashMap(), null);
    System.out.println(res);
    ETest01 eTest01 = gson.fromJson(res, ETest01.class);
    String dbUserName=“root”;//定义用户名,写你想要连接到的用户。
    String dbPassword=“root”;//用户密码。
    String dbUrl=“jdbc:mysql://localhost:3306/aa?”+“useUnicode=true&characterEncoding=UTF8”;
    Connection con=DriverManager.getConnection(dbUrl,dbUserName,dbPassword);
    Statement stmt=con.createStatement();
    //定义需要获取json格式中的字段
    String cameraIndexCode;
    String cameraName;
    String cameraTypeName;
    Integer channelNo;
    String encodeDevIndexCode;
    String gbIndexCode;
    String regionIndexCode;
    String updateTime;
    for (ETest01.DataBean datum : eTest01.getData()) {
    cameraIndexCode = datum.getCameraIndexCode();
    cameraName = datum.getCameraName();
    cameraTypeName = datum.getCameraTypeName();
    channelNo = datum.getChannelNo();
    encodeDevIndexCode = datum.getRegionIndexCode();
    gbIndexCode = datum.getGbIndexCode();
    regionIndexCode = datum.getRegionIndexCode();
    updateTime = datum.getUpdateTime();
    int rs=stmt.executeUpdate(“insert into sys_hai_kang(camera_Index_Code,camera_Name,camera_Type_Name,channel_No,encode_Dev_Index_Code,gb_Index_Code,region_Index_Code,update_Time) values (’”+cameraIndexCode+"’,’"+cameraName+"’,’"+cameraTypeName+"’,’"+channelNo+"’,’"+encodeDevIndexCode+"’,’"+gbIndexCode+"’,’"+regionIndexCode+"’,’"+updateTime+"’)");//执行sql并返还结束 ;ResultSet executeQuery(String sqlString):用于返还一个结果集(ResultSet)对象。

     }
     if(stmt!=null){//关闭说明对象
         try{
             stmt.close();
         }catch(SQLException e){
             e.printStackTrace();
         }
     }
     if(con!=null){//关闭连接
         try{
             con.close();
         }catch(SQLException e){
             e.printStackTrace();
         }
    
     }
    

    }
    }




你可能感兴趣的:(java,json,big,data)