[toc]
HttpClient接口调用
pom.xml文件配置
commons-httpclient
commons-httpclient
3.1
额外知识点
想直奔主题的童鞋,可跳过该步骤
将接口常量配置到配置文件中(笔者使用的Spring Boot)
修改.yml文件
wbFrame:
# 行情对接配置信息
quote:
quoteUrl: http://192.168.100.24:8080/api/service/depthMarketData
tokenUrl: http://192.168.100.24:8080/api/getAccessToken
loginUrl: http://192.168.102.150:8080/api/service/futuresAccountLogin
获取配置文件中的信息
package net.qmgf.proj.wbmining.common.config;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 获取配置文件中信息config
*/
@ConfigurationProperties(prefix = "wbFrame")
@Component
@Data
@NoArgsConstructor
public class WBFrameProperties {
/**
* 行情对接配置
*/
private Quote quote;
/**
* 行情对接配置信息
*
* @author He
*/
@Data
@NoArgsConstructor
public static class Quote {
/**
* 获取内外盘行情url
*/
private String quoteUrl;
/**
* 获取token的url
*/
private String tokenUrl;
/**
* 获取账号登录的url
*/
private String loginUrl;
}
}
DTO & JSON 互相转换
import com.alibaba.fastjson.JSON;
// dto 转 json
String json = JSON.toJSONString(dto)
// json 转 dto
DTO dto = JSON.parseObject(str, DTO.class)
接口对接
LoginDataCtpDto
这里的接口传入和接收DTO都用这一个了,请允许笔者偷懒(手动滑稽)。
package
net.qmgf.proj.wbmining.fut.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import net.qmgf.frame.common.base.model.BaseEntityDto;
/**
*
* @author He
* @date 2020年6月9日
* @version 1.0
*
*/
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@ApiModel(value = "ctp账号登录信息")
public class LoginDataCtpDto extends BaseEntityDto {
private static final long serialVersionUID = 1L;
/**
* 经纪商ID
*/
@ApiModelProperty(value = "经纪商ID")
private String brokerId;
/**
* 用户ID
*/
@ApiModelProperty(value = "用户ID")
private String userId;
/**
* 登录状态
*/
@ApiModelProperty(value = "登录状态")
private Boolean loginStatus;
}
LoginCtpDto
package
net.qmgf.proj.wbmining.fut.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.List;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import net.qmgf.frame.common.base.model.BaseEntityDto;
/**
*
* @author He
* @date 2020年6月9日
* @version 1.0
*
*/
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@ApiModel(value = "ctp账号登录返回信息")
public class LoginCtpDto extends BaseEntityDto {
private static final long serialVersionUID = 1L;
/**
* 状态
*/
@ApiModelProperty(value = "状态")
private Boolean status;
/**
* data
*/
@ApiModelProperty(value = "data")
private List data;
}
接口实现
package
net.qmgf.proj.wbmining.quote.service.impl;
import java.util.List;
import net.qmgf.frame.common.base.service.impl.BaseServiceImpl;
import net.qmgf.proj.wbmining.base.entity.DdFutureCompany;
import net.qmgf.proj.wbmining.base.service.IDdFutureCompanyService;
import net.qmgf.proj.wbmining.common.config.WBFrameProperties;
import net.qmgf.proj.wbmining.form.service.impl.IndexFormServiceImpl;
import net.qmgf.proj.wbmining.fut.dto.LoginCtpDto;
import net.qmgf.proj.wbmining.fut.dto.LoginDataCtpDto;
import net.qmgf.proj.wbmining.quote.dto.QuoteFuturesAccountDto;
import net.qmgf.proj.wbmining.quote.entity.QuoteFuturesAccount;
import net.qmgf.proj.wbmining.quote.mapper.QuoteFuturesAccountMapper;
import net.qmgf.proj.wbmining.quote.service.IQuoteFuturesAccountService;
import net.qmgf.proj.wbmining.quote.service.IQuotePreAddressService;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.itextpdf.text.log.Logger;
import com.itextpdf.text.log.LoggerFactory;
/**
*
* 期货账号密码 服务实现类
*
*
* @author qmgf
* @since 2020-05-12
*/
@Service
public class QuoteFuturesAccountServiceImpl extends BaseServiceImpl implements
IQuoteFuturesAccountService {
private static final Logger logger = LoggerFactory.getLogger(IndexFormServiceImpl.class);
private static final int readTimeOut = 30000;
private static final int conTimeOut = 30000;
@Autowired
private IDdFutureCompanyService ddFutureCompanyService;
@Autowired
private WBFrameProperties wBFrameProperties;
/**
* 登录
*
* @author He
* @date 2020年6月9日
* @version 1.0
*
* @param quoteFuturesAccount
* @return
*/
@Override
public Boolean signIn(QuoteFuturesAccountDto quoteFuturesAccount) {
Boolean loginStatus = false;
// 获取配置文件的信息
// String token = JwtUtil.getAccessToken("admin", "PC");
String tokenUrl = wBFrameProperties.getQuote().getTokenUrl();
// String postUrl = "http://192.168.102.150:8080/api/service/futuresAccountLogin";
String postUrl = wBFrameProperties.getQuote().getLoginUrl();
// 数据准备
DdFutureCompany futureCompany = ddFutureCompanyService.selectById(quoteFuturesAccount.getBrokerId());
String fcompanyCode = futureCompany.getFcompanyCode();
LoginDataCtpDto dataDto = new LoginDataCtpDto();
dataDto.setUserId(quoteFuturesAccount.getUserAccount());
dataDto.setBrokerId(fcompanyCode);
// Dto转Json
String requestBody = JSON.toJSONString(dataDto);
try {
// 接口调用
String response = httpPost(postUrl, tokenUrl, requestBody);
// Json转Dto
LoginCtpDto dto = JSON.parseObject(response, LoginCtpDto.class);
List data = dto.getData();
if (data != null && data.size() > 0) {
loginStatus = data.get(0).getLoginStatus();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return loginStatus;
}
/**
* 接口调用HTTP POST
*
* @param url
* @param token
* @param requestBody
* @return
* @throws Exception
*/
public String httpPost(String url, String token, String requestBody) throws Exception {
String response = null;
PostMethod postMethod = null;
logger.info("访问:" + url);
try {
HttpClient client = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
postMethod = new PostMethod(url);
postMethod.setRequestHeader("Connection", "close");
if (!token.isEmpty()) {
postMethod.setRequestHeader("Authorization", token);
}
postMethod.getParams().setParameter("http.protocol.content-charset", "utf-8");
logger.info("请求数据:" + requestBody);
postMethod.setRequestBody(new NameValuePair[] { new NameValuePair("requestBody", requestBody) });
HttpConnectionManagerParams managerParams = client.getHttpConnectionManager().getParams();
postMethod.getParams().setParameter("http.method.retry-handler", new DefaultHttpMethodRetryHandler(1, false));
managerParams.setConnectionTimeout(conTimeOut);
managerParams.setSoTimeout(readTimeOut);
client.executeMethod(postMethod);
if (postMethod.getStatusCode() == 200) {
response = postMethod.getResponseBodyAsString();
logger.info("访问:" + url + " 响应数据:" + response);
} else {
logger.error("访问:" + url + "异常,响应状态码:" + postMethod.getStatusCode() + ",响应内容:"
+ postMethod.getResponseBodyAsString());
}
} finally {
if (postMethod != null) {
postMethod.releaseConnection();
}
}
return response;
}
}