一.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);
}
}