目录
1.http请求(get)
一般用来获取查询接口
(1)从前端获取到参数,拼接到http请求后面,调用http请求方法,调用成功后将返回的结果进行处理
Map paramMap = PJCommon.getRequestParamMap(request);
if (paramMap.containsKey("code")
&&!StringUtils.isEmpty(paramMap.get("code"))) {
String code = paramMap.get("code").toString();
param+="?spSource="+code;
}
if (paramMap.containsKey("startTime")
&&!StringUtils.isEmpty(paramMap.get("startTime"))) {
String startTime = paramMap.get("startTime").toString();
param+="&beginDate="+startTime;
}
if (paramMap.containsKey("endTime")
&&!StringUtils.isEmpty(paramMap.get("endTime"))) {
String endTime = paramMap.get("endTime").toString();
param+="&endDate="+endTime;
}
String url=yx_url+param;
System.out.println("请求地址:"+url);
String result = HttpClient.httpRequest(url);
List list = new ArrayList();
if(null!=result && !result.equals("")){
JSONObject object = JSONObject.parseObject(result.toString());
boolean success =(boolean) object.get("success");
if(success){
if(object!=null){
String data = object.get("body").toString();
list = JSONArray.parseArray(data);
}
}
}
(2)http请求方法(https使用的是同一个方法):
/**
* 发送http请求
*
* @param requestUrl 请求地址
* @return String
*/
public static String httpRequest(String requestUrl) {
StringBuffer buffer = new StringBuffer();
try {
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
httpUrlConn.setDoInput(true);
httpUrlConn.setRequestMethod("GET");
httpUrlConn.connect();
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return buffer.toString();
}
2.http请求(post)
一般用来请求新增、修改、删除的接口
(1)将参数封装为json格式
Map map1 = new HashMap();
map1.put("spId",yxCode);
if(null!=tOrderWeighHf){
map1.put("ashAd",tOrderWeighHf.getaAd());
map1.put("ashAar",tOrderWeighHf.getaAar());
}else{
map1.put("ashAd",null);
map1.put("ashAar",null);
}
if(null!=tOrderWeighQssf){
map1.put("moisture",tOrderWeighQssf.getMtPj());
}else{
map1.put("moisture",null);
}
if(null!=tOrderWeighHff){
map1.put("volatileRate",tOrderWeighHff.getaVdaf());
}else{
map1.put("volatileRate",null);
}
if(null!=vulcanization){
map1.put("totalSulfur",vulcanization.getStD());
}else{
map1.put("totalSulfur",null);
}
if(null!=tOrderCaloric){
map1.put("heatCal",tOrderCaloric.getCalG());
String objMjKg = tOrderCaloric.getMjKg().stripTrailingZeros().toPlainString();
double dbMjKg = Double.valueOf(objMjKg);
toolXy tt=new toolXy();
double mjKg =tt.get2Xy(dbMjKg);// 修约 2位
map1.put("heatMj",mjKg);
}else{
map1.put("heatCal",null);
map1.put("heatMj",null);
}
map1.put("wasteRate",0);
//传入的参数
String param = JSON.toJSONString(map1);
(2)传入http请求地址和参数,调用http请求方法,请求成功后,将获取到的结果解析
(3)http请求post方法:
/**
* post请求
* @param url
* @param param
* @return
*/
public static String httpsPost(String url,String param){
HttpURLConnection httpURLConnection = null;
OutputStream out = null; //写
InputStream in = null; //读
int responseCode = 0; //远程主机响应的HTTP状态码
String result="";
try{
URL sendUrl = new URL(url);
httpURLConnection = (HttpURLConnection)sendUrl.openConnection();
//post方式请求
httpURLConnection.setRequestMethod("POST");
//设置头部信息
httpURLConnection.setRequestProperty("headerdata", "ceshiyongde");
//一定要设置 Content-Type 要不然服务端接收不到参数
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
//指示应用程序要将数据写入URL连接,其值默认为false(是否传参)
httpURLConnection.setDoOutput(true);
//httpURLConnection.setDoInput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setConnectTimeout(30000); //30秒连接超时
httpURLConnection.setReadTimeout(30000); //30秒读取超时
//传入参数
out = httpURLConnection.getOutputStream();
byte[] bytes = param.getBytes();
out.write(param.getBytes());
out.flush(); //清空缓冲区,发送数据
out.close();
responseCode = httpURLConnection.getResponseCode();
//获取请求的资源
BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"UTF-8"));
result =br.readLine();
}catch(Exception e) {
e.printStackTrace();
log.error("https请求异常:{}", e);
}
return result;
}
3.https请求(get)
(1)请求地址拼接请求参数
StringBuilder sb = new StringBuilder(url);
sb.append("?appId=" + APP_ID + "&signature=" + signature + "&format=" + format + "&nonce=" + nonce + "&pageIndex=" + currentPage + "&pageSize=" + pagesize + "×tamp=" + timestamp + "&openUid=" + openUid + "");
String requestUrl = sb.toString();
(2)传入http请求地址,调用https请求方法,请求成功后,将获取到的结果转换为json对象格式,获取结果
/**
* 调用https请求get
*
* @return
*/
int currentPage=1;//当前页
int pagesize=10;//每页多少条
int totalCount=0;//总条数
String MOOC_OPENUID = "";
int flg=0;
int totalPageCount=0;//总页数
//获取https请求
public void learnGrogress(String requestUrl,JdbcTemplate jdbcTemplate,String openUid){
try{
log.info("=================进入调用==================");
String respXml = HttpsClient.httpRequest(requestUrl);
// respXml=respXml.substring(respXml.indexOf("(")+1,respXml.length()-1);
JSONObject jsonObject =null;
jsonObject=JSONObject.parseObject(respXml);
if(null==jsonObject){
log.info("=================接口信息为空==================");
return ;
}else{
Object code_obj=jsonObject.get("code");
if(null!=code_obj){
String stateCode=code_obj.toString();
if(!"200".equals(stateCode)){
log.info("=================接口错误码==================");
log.info("================访问接口的返回码:"+stateCode+"==================");
return;
}
}
}
JSONObject result = (JSONObject) jsonObject.get("result");
JSONObject learningInfo = (JSONObject) result.get("learningInfo");
JSONObject queryMeta = (JSONObject) result.get("queryMeta");
int dqy = Integer.parseInt(queryMeta.get("pageIndex").toString());//当前,请求的页数,pageIndex从1开始,表示第一页
totalPageCount = Integer.parseInt(queryMeta.get("totalPageCount").toString());//返回结果总页数
int pageSize = Integer.parseInt(queryMeta.get("pageSize").toString());//每页大小,默认15条
totalCount = Integer.parseInt(queryMeta.get("totalCount").toString());//返回结果总数据条数
}catch (Exception e) {
e.printStackTrace();
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
Long timeC = System.currentTimeMillis();
String ID = uuid + timeC;//
Date end = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = sdf.format(end);
String exceptionString="发生异常:"+e.toString();
if(exceptionString.length()>100){
exceptionString=exceptionString.substring(0,99);
}
}
//System.out.println("==========================业务执行完毕=========================");
}
(3)https请求方法:
/**
* 发送http请求
*
* @param requestUrl 请求地址
* @return String
*/
public static String httpRequest(String requestUrl) {
StringBuffer buffer = new StringBuffer();
try {
//trustAllHosts();
SslUtils.ignoreSsl();
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
//httpUrlConn.setHostnameVerifier(DO_NOT_VERIFY);
httpUrlConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
httpUrlConn.setDoInput(true);
httpUrlConn.setRequestMethod("GET");
httpUrlConn.connect();
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return buffer.toString();
}