java調用接口之http方式

一.http調用類

package com.tbl.common.utils;

import com.alibaba.fastjson.JSON;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * http調用共同類
 *
 */
public class HttpUtil {

    //返回數據類型(1:字符串;2:字節數組)
    private static final Integer RETURN_TYPE_STRING = 1;

    /**
     * http post 方法調用(content-type: application/json)
     * @param url
     * @param params
     * @return 響應數據
     */
    public static String postJSON(String url, String params, Map<String, Object> headers) {
        return (String) postJSONWithResponseHeaders(url, params, headers).get("data");
    }

    /**
     * 調用指定url返回數據(method: post, content-type: application/json)
     * @param url
     * @param parameters
     * @param headers
     * @return
     */
    public static Map<String, Object> postJSONWithResponseHeaders(String url, String parameters, Map<String, Object> headers) {
        HttpPost httppost = new HttpPost(url);

//        String parameters = JSON.toJSONString(params);

        if (StringUtils.isEmpty(parameters)) {
            return httpInternelExecute(httppost, headers, RETURN_TYPE_STRING);
        }

        StringEntity entity = new StringEntity(parameters, ContentType.create("application/json", Consts.UTF_8));
        entity.setChunked(true);
        httppost.setEntity(entity);

        return httpInternelExecute(httppost, headers, RETURN_TYPE_STRING);
    }

    /**
     * 執行http請求並返回結果
     * @param httpUriRequest
     * @param reqHeaders
     * @param type 返回數據類型(1:字符串;2:字節數組)
     * @return {
     *     responseHeaders:響應頭Map
     *     data: 返回結果(String or byte array)
     * }
     */
    private static Map<String, Object> httpInternelExecute(HttpUriRequest httpUriRequest, Map<String, Object> reqHeaders, Integer type) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        BufferedReader reader = null;

        try {
            if (reqHeaders != null) {
                for (String key : reqHeaders.keySet()) {
                    httpUriRequest.setHeader(key, (String) reqHeaders.get(key));
                }
            }

            response = httpclient.execute(httpUriRequest);

            StatusLine statusLine = response.getStatusLine();
            HttpEntity entity = response.getEntity();
            if (statusLine.getStatusCode() >= 300) {
                throw new HttpResponseException(
                        statusLine.getStatusCode(),
                        statusLine.getReasonPhrase());
            }

            if (entity == null) {
                throw new ClientProtocolException("Response contains no content");
            }

            InputStream inputStream = entity.getContent();
            Object data = null;

            //判斷是要返回字符串
            if (type.equals(RETURN_TYPE_STRING)) {
                reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("utf-8")));

                StringBuilder sb = new StringBuilder(1024);

                String item;
                while ((item = reader.readLine()) != null) {
                    sb.append(item + "\n");
                }

                String s = sb.toString();
                if (StringUtils.isNotEmpty(s)) {
                    data = s.substring(0, s.length() - 1);
                }

            } else { //返回字節數組
                new IllegalStateException();
            }

            Header[] headers = response.getAllHeaders();
            Map<String, Object> responseHeaders = new HashMap<String, Object>();

            for (int i = 0; i < headers.length; i++) {
                responseHeaders.put(headers[i].getName(), headers[i].getValue());
            }
            Map<String, Object> result = new HashMap<String, Object>(2);
            result.put("responseHeaders", responseHeaders);
            result.put("data", data);

            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

}

二:示例  比如調用一個簡單的顧客接口

1.通過Test測試接口

     // 顧客接口
      @Test
      public void setPOInstock() {

        //接口地址
        String url="";

        JSONArray cusArr = new JSONArray();
        JSONObject matObj1 = new JSONObject();
        matObj1.put("id", 99);
        matObj1.put("customerCode", "HK000008");
        matObj1.put("customerName", "公司");
        matObj1.put("customerType", "個體");
        matObj1.put("linkman", "天玄1");
        matObj1.put("telephone", "1518972584");
        cusArr.add(matObj1);

        Map<String, Object> map= HttpUtil.postJSONWithResponseHeaders(url ,JSONArray.toJSONString(cusArr), null);
        System.out.println(map);
    }

2.通過postman調用接口

注1:postman調用類型,圖片中爲post方式。                                 

2:接口路徑,圖中爲調用本地的路徑

3:接口傳輸的數據  

4:調用接口後的返回值。

 

 附 實現層代碼

package com.tbl.modules.erpInterface.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.tbl.common.utils.DateUtils;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.basedata.dao.CustomerDAO;
import com.tbl.modules.basedata.entity.Customer;
import com.tbl.modules.erpInterface.service.CustomerErpInterfaceService;
import com.tbl.modules.platform.service.system.InterfaceLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @program: dyyl
 * @description: 生成顧客與供應商調用接口service實現
 * @author: pz
 * @create: 2019-02-15
 **/
@Service("customerErpInterfaceService")
public class CustomerErpInterfaceServiceImpl implements CustomerErpInterfaceService {

    @Autowired
    private CustomerDAO customerDAO;

    @Autowired
    private InterfaceLogService interfaceLogService;
    /**
     * 生成客戶信息
     * @author pz
     * @date 2019-02-15
     * @param customerInfo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String customerInfo(String customerInfo) {

        String nowDate = DateUtils.getTime();

        JSONArray customerArr = JSON.parseArray(customerInfo);
        JSONObject resultObj = new JSONObject();
        for (int i=0;i<customerArr.size();i++) {

            JSONObject customerInfoObj = customerArr.getJSONObject(i);
            Long cusId=customerInfoObj.getLong("id");
            if(cusId==null) {
                resultObj.put("msg", "顧客id不能爲空!");
                resultObj.put("success", false);
                return JSON.toJSONString(resultObj);
            }
            Customer cust=customerDAO.selectById(cusId);
            //顧客編碼
            String   customerCode=customerInfoObj.getString("customerCode");
            //顧客名稱
            String   customerName=customerInfoObj.getString("customerName");
            //顧客類型
            String   customerType=customerInfoObj.getString("customerType");
            //聯繫人
            String   linkman=customerInfoObj.getString("linkman");
            //聯繫電話
            String   telephone=customerInfoObj.getString("telephone");
            //地址
            String   address=customerInfoObj.getString("address");
            //郵箱
            String   mail=customerInfoObj.getString("mail");
            //備註
            String   remark=customerInfoObj.getString("remark");

            if(StringUtils.isEmpty(customerCode)) {
                resultObj.put("msg", "顧客編碼不能爲空!");
                resultObj.put("success", false);
                return JSON.toJSONString(resultObj);
            }

            if(StringUtils.isEmpty(customerName)) {
                resultObj.put("msg", "顧客名稱不能爲空!");
                resultObj.put("success", false);
                return JSON.toJSONString(resultObj);
            }

            if(cust==null){

                EntityWrapper<Customer> customerEntity = new EntityWrapper<>();
                customerEntity.eq("customer_code",customerCode);
                int count = customerDAO.selectCount(customerEntity);

                if(count>0) {
                    resultObj.put("msg", "顧客編碼不能重複!");
                    resultObj.put("success", false);
                    return JSON.toJSONString(resultObj);
                }

                boolean customerResult =  customerDAO.savaCustomer(cusId,customerCode, customerName,customerType,
                        linkman,telephone, address,mail, remark,nowDate);
                if (customerResult) {
                    resultObj.put("msg", "顧客添加成功!");
                    resultObj.put("success", true);
                    interfaceLogService.interfaceLogInsert("顧客調用接口",customerInfoObj.getString("customerCode"),resultObj.get("msg").toString(),nowDate);
                } else {
                    resultObj.put("msg", "顧客添加失敗原因:“添加失敗”!");
                    resultObj.put("success", false);
                    interfaceLogService.interfaceLogInsert("顧客調用接口",customerInfoObj.getString("customerCode"),resultObj.get("msg").toString(),nowDate);
                    return JSON.toJSONString(resultObj);
                }
            }else{

                // 保存客戶實體
                cust.setCustomerCode(customerCode);
                cust.setCustomerName(customerName);
                cust.setCustomerType(customerType);
                cust.setLinkman(linkman);
                cust.setTelephone(telephone);
                cust.setAddress(address);
                cust.setMail(mail);
                cust.setRemark(remark);
                cust.setUpdateTime(nowDate);

                boolean updateCustomerResult =  customerDAO.updateById(cust)>0;

                if (updateCustomerResult) {
                    resultObj.put("msg", "顧客修改成功!");
                    resultObj.put("success", true);
                    interfaceLogService.interfaceLogInsert("顧客調用接口",customerInfoObj.getString("customerCode"),resultObj.get("msg").toString(),nowDate);
                } else {
                    resultObj.put("msg", "失敗原因:“顧客修改失敗”!");
                    resultObj.put("success", false);
                    interfaceLogService.interfaceLogInsert("顧客調用接口",customerInfoObj.getString("customerCode"),resultObj.get("msg").toString(),nowDate);
                    return JSON.toJSONString(resultObj);
                }
            }

        }

        return JSON.toJSONString(resultObj);
    }

}
    

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章