获取第三方接口
1.HttpUtils工具类
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.util.*;
public class HttpUtils {
public static String doPost(String url, Map<String,String> map, String charset){
CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try{
httpClient = HttpClients.createDefault();
httpPost = new HttpPost(url);
//设置参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<String,String> elem = (Map.Entry<String, String>) iterator.next();
list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
}
if(list.size() > 0){
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);
httpPost.setEntity(entity);
}
HttpResponse response = httpClient.execute(httpPost);
if(response != null){
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
result = EntityUtils.toString(resEntity,charset);
}
}
}catch(Exception ex){
ex.printStackTrace();
}
return result;
}
}
2.访问接口
@Api(value = "/", tags = "账单相关接口")
@Controller
@RequestMapping("/merchant")
public class MerchantController {
private static final Logger logger = LoggerFactory.getLogger(MerchantController.class);
@Value("${merchantUrl}")
private String merchantUrl;
@RequestMapping(value = "getDetail", method = RequestMethod.GET)
@ApiOperation(value = "获取详情")
@ResponseBody
public RtnInfo getDetail(@ApiParam("账单id") @RequestParam(value = "id") String id) {
logger.info("getDetail ============================>begin");
logger.info("getDetail param: id=" + id);
RtnInfo rtnInfo = new RtnInfo();
Map<String, String> params = new HashMap<String, String>();
params.put("id", id);
String returnObj = HttpUtils.doPost(merchantUrl + "/logistics/free/getDetail", params, "utf-8");
if (StringUtils.isBlank(returnObj)) {
rtnInfo.setSystemCode(SystemCode.ERROR_5);
rtnInfo.setMsg("接口返回无数据!");
return rtnInfo;
}
RtnInfo returnData = JSONObject.parseObject(returnObj, RtnInfo.class);
if (returnData.getCode().equals("0")) {
rtnInfo.setData(returnData.getData());
rtnInfo.setSystemCode(SystemCode.SUCCESS);
} else {
rtnInfo.setData(null);
rtnInfo.setSystemCode(SystemCode.ERROR_5);
rtnInfo.setMsg(returnData.getMsg());
}
logger.info("returnResult:" + rtnInfo.toString());
logger.info("getDetail ============================>end");
return rtnInfo;
}
}