From a7984290ba1d51a02a8c50dac9a2fce8e1dfaf90 Mon Sep 17 00:00:00 2001 From: xyiege Date: Fri, 16 Sep 2022 17:29:39 +0800 Subject: [PATCH] =?UTF-8?q?=E5=88=87=E6=8D=A2httpclient=E5=8C=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cn/chjyj/szwh/utils/RequestUtils.java | 76 ++++++++++--------- .../java/cn/chjyj/szwh/utils/SzFileUtils.java | 31 ++++++-- urls.md | 8 +- 3 files changed, 72 insertions(+), 43 deletions(-) diff --git a/src/main/java/cn/chjyj/szwh/utils/RequestUtils.java b/src/main/java/cn/chjyj/szwh/utils/RequestUtils.java index 924ae7d..0b30fe1 100644 --- a/src/main/java/cn/chjyj/szwh/utils/RequestUtils.java +++ b/src/main/java/cn/chjyj/szwh/utils/RequestUtils.java @@ -5,14 +5,20 @@ import com.alibaba.fastjson2.JSONObject; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpEntity; +import org.apache.http.HttpStatus; import org.apache.http.StatusLine; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.HttpClient; +import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; -import org.springframework.http.HttpStatus; + import java.io.IOException; import java.io.InputStream; @@ -28,47 +34,45 @@ public class RequestUtils { private static Log logger = LogFactory.getLog(RequestUtils.class); /** - * 能设置请求头的get方式 - * @param surl + * httpclient 方式获取信息 + * @param url * @param map - * @param wflag 是否写入json文件 + * @param wflag * @return */ - public static JSONObject GetData(String surl, Map map,boolean wflag){ + public static JSONObject GetData(String url,Map map,boolean wflag){ JSONObject jsonObject = new JSONObject(); - try{ - URL url = new URL(surl); - HttpURLConnection httpcon = (HttpURLConnection) url.openConnection(); - // 遍历主机头信息 - for(Map.Entry item:map.entrySet()){ - httpcon.addRequestProperty( - item.getKey().toString(), - item.getValue().toString() - ); - } - httpcon.setConnectTimeout(6000); - httpcon.connect(); - //获取返回的字符 - InputStream inputStream = httpcon.getInputStream(); - //请求结果写入 - String filename =String.valueOf(Calendar.getInstance().getTimeInMillis()); - if(wflag){ - SzFileUtils.createFile(inputStream,filename); - //字节转为utf-8 - String message=SzFileUtils.readJson(filename); - if(message!=null){ - jsonObject = JSONObject.parseObject(message); - logger.info("respone message :"+message); - } - logger.info("respone message is null"); + String result = StringUtils.EMPTY; + CloseableHttpClient httpClient = HttpClients.createDefault(); + HttpGet httpGet = new HttpGet(url); + // 其他附加参数 + for(Map.Entry item:map.entrySet()){ + httpGet.addHeader(item.getKey().toString(), + item.getValue().toString()); + } + + httpGet.setConfig(RequestConfig.custom().setConnectTimeout(1000).build()); + try { + CloseableHttpResponse response = httpClient.execute(httpGet); + int status = response.getStatusLine().getStatusCode(); + if (status == HttpStatus.SC_OK){ + HttpEntity responseEntity = response.getEntity(); + result = EntityUtils.toString(responseEntity, "UTF-8"); + logger.info("api Request结果:"+result); + jsonObject = JSONObject.parseObject(result); } - }catch (IOException ex){ - // 罗列出明细错误 - logger.error("请求错误:"+ex); - ex.printStackTrace(); + // 转换为jsonobject + logger.info("httpGet状态:"+status); + } catch (ClientProtocolException e) { + logger.error("请求错误:"+e); + e.printStackTrace(); + } catch (IOException e) { + logger.error("请求错误:"+e); + e.printStackTrace(); } return jsonObject; } + /** * 利用GET方式获取uri数据 * @param requri 请求地址 @@ -134,7 +138,7 @@ public class RequestUtils { response = httpClient.execute(httpPost); StatusLine httpStatus = response.getStatusLine(); int status = httpStatus.getStatusCode(); - if(status== HttpStatus.OK.value()){ //状态码 为200 + if(status== HttpStatus.SC_OK){ //状态码 为200 String outs = EntityUtils.toString(response.getEntity()); jsonObject = JSONObject.parseObject(outs); } @@ -171,7 +175,7 @@ public class RequestUtils { response = httpClient.execute(httpPost); StatusLine httpStatus = response.getStatusLine(); int status = httpStatus.getStatusCode(); - if(status== HttpStatus.OK.value()){ //状态码 为200 + if(status== HttpStatus.SC_OK){ //状态码 为200 //String outs = response.getEntity().toString(); String outs = EntityUtils.toString(response.getEntity()); return outs; diff --git a/src/main/java/cn/chjyj/szwh/utils/SzFileUtils.java b/src/main/java/cn/chjyj/szwh/utils/SzFileUtils.java index f4c276b..9b9dc91 100644 --- a/src/main/java/cn/chjyj/szwh/utils/SzFileUtils.java +++ b/src/main/java/cn/chjyj/szwh/utils/SzFileUtils.java @@ -1,6 +1,9 @@ package cn.chjyj.szwh.utils; import cn.chjyj.szwh.configure.EnvConfig; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.io.*; import java.text.SimpleDateFormat; @@ -11,6 +14,7 @@ import java.util.Calendar; * xy */ public class SzFileUtils { + private static Log logger = LogFactory.getLog(SzFileUtils.class); /** * 读取pem文件信息内容,并返回字符串 * @@ -81,18 +85,23 @@ public class SzFileUtils { String path= EnvConfig.yxDbConf()+File.separator+folder+filename+".json"; File fdFile = new File(folder); // 检查目录是否存在 - if(!fdFile.exists()){ + if(!fdFile.isDirectory() && !fdFile.exists()){ fdFile.mkdirs(); } int index; byte[] bytes = new byte[1024]; try { - FileOutputStream jsonFile = new FileOutputStream(path); - while ((index = inputStream.read(bytes)) != -1) { - jsonFile.write(bytes, 0, index); - jsonFile.flush(); + // append 追加到当前文件 + FileOutputStream jsonFile = new FileOutputStream(path,true); + if(inputStream.available()>0){ + while ((index = inputStream.read(bytes)) != -1) { + jsonFile.write(bytes, 0, index); + jsonFile.write("\r\n".getBytes()); + jsonFile.flush(); + } } jsonFile.close(); + logger.info("inputstream size :"+inputStream.available()); inputStream.close(); }catch (Exception ex){ ex.printStackTrace(); @@ -115,8 +124,18 @@ public class SzFileUtils { try { InputStream ins = new FileInputStream(fdFile); BufferedReader br = new BufferedReader(new InputStreamReader(ins)); - String readLine = null; + String lineStr = ""; StringBuffer sb = new StringBuffer(); + while ((lineStr = br.readLine()) != null) { + if(!StringUtils.contains(lineStr,"isliCode")){ + // del + fdFile.delete(); + }else{ + sb.append(lineStr); + } + } + br.close(); + ins.close(); return sb.toString(); }catch (Exception ex){ ex.printStackTrace(); diff --git a/urls.md b/urls.md index 000f8f4..9358aad 100644 --- a/urls.md +++ b/urls.md @@ -28,4 +28,10 @@ 13. [SpringBoot+Quartz+数据库存储+Quartz四大应用场景](https://blog.csdn.net/Lzxccas/article/details/110561320) -14. [SpringBoot自动配置Quartz](https://www.shouxicto.com/article/2060.html) \ No newline at end of file +14. [SpringBoot自动配置Quartz](https://www.shouxicto.com/article/2060.html) + +15 . [JAVA获取Get请求的InputStream,将InputStream写到本地文件中](https://www.cnblogs.com/wwssgg/p/15501060.html) + +16.[字节流InputStream和OutputStream、向文件读写内容](https://blog.csdn.net/Tir_zhang/article/details/124733876) + +17.[StringUtils工具类常用方法](https://www.cnblogs.com/jmcui/p/7208383.html) \ No newline at end of file