Browse Source

切换httpclient包

master
xyiege 3 years ago
parent
commit
a7984290ba
  1. 76
      src/main/java/cn/chjyj/szwh/utils/RequestUtils.java
  2. 31
      src/main/java/cn/chjyj/szwh/utils/SzFileUtils.java
  3. 6
      urls.md

76
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.lang3.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; 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.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.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpStatus;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -28,47 +34,45 @@ public class RequestUtils {
private static Log logger = LogFactory.getLog(RequestUtils.class); private static Log logger = LogFactory.getLog(RequestUtils.class);
/** /**
* 能设置请求头的get方式 * httpclient 方式获取信息
* @param surl * @param url
* @param map * @param map
* @param wflag 是否写入json文件 * @param wflag
* @return * @return
*/ */
public static JSONObject GetData(String surl, Map<String,Object> map,boolean wflag){ public static JSONObject GetData(String url,Map<String,Object> map,boolean wflag){
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
try{ String result = StringUtils.EMPTY;
URL url = new URL(surl); CloseableHttpClient httpClient = HttpClients.createDefault();
HttpURLConnection httpcon = (HttpURLConnection) url.openConnection(); HttpGet httpGet = new HttpGet(url);
// 遍历主机头信息 // 其他附加参数
for(Map.Entry item:map.entrySet()){ for(Map.Entry item:map.entrySet()){
httpcon.addRequestProperty( httpGet.addHeader(item.getKey().toString(),
item.getKey().toString(), item.getValue().toString());
item.getValue().toString() }
);
} httpGet.setConfig(RequestConfig.custom().setConnectTimeout(1000).build());
httpcon.setConnectTimeout(6000); try {
httpcon.connect(); CloseableHttpResponse response = httpClient.execute(httpGet);
//获取返回的字符 int status = response.getStatusLine().getStatusCode();
InputStream inputStream = httpcon.getInputStream(); if (status == HttpStatus.SC_OK){
//请求结果写入 HttpEntity responseEntity = response.getEntity();
String filename =String.valueOf(Calendar.getInstance().getTimeInMillis()); result = EntityUtils.toString(responseEntity, "UTF-8");
if(wflag){ logger.info("api Request结果:"+result);
SzFileUtils.createFile(inputStream,filename); jsonObject = JSONObject.parseObject(result);
//字节转为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");
} }
}catch (IOException ex){ // 转换为jsonobject
// 罗列出明细错误 logger.info("httpGet状态:"+status);
logger.error("请求错误:"+ex); } catch (ClientProtocolException e) {
ex.printStackTrace(); logger.error("请求错误:"+e);
e.printStackTrace();
} catch (IOException e) {
logger.error("请求错误:"+e);
e.printStackTrace();
} }
return jsonObject; return jsonObject;
} }
/** /**
* 利用GET方式获取uri数据 * 利用GET方式获取uri数据
* @param requri 请求地址 * @param requri 请求地址
@ -134,7 +138,7 @@ public class RequestUtils {
response = httpClient.execute(httpPost); response = httpClient.execute(httpPost);
StatusLine httpStatus = response.getStatusLine(); StatusLine httpStatus = response.getStatusLine();
int status = httpStatus.getStatusCode(); int status = httpStatus.getStatusCode();
if(status== HttpStatus.OK.value()){ //状态码 为200 if(status== HttpStatus.SC_OK){ //状态码 为200
String outs = EntityUtils.toString(response.getEntity()); String outs = EntityUtils.toString(response.getEntity());
jsonObject = JSONObject.parseObject(outs); jsonObject = JSONObject.parseObject(outs);
} }
@ -171,7 +175,7 @@ public class RequestUtils {
response = httpClient.execute(httpPost); response = httpClient.execute(httpPost);
StatusLine httpStatus = response.getStatusLine(); StatusLine httpStatus = response.getStatusLine();
int status = httpStatus.getStatusCode(); int status = httpStatus.getStatusCode();
if(status== HttpStatus.OK.value()){ //状态码 为200 if(status== HttpStatus.SC_OK){ //状态码 为200
//String outs = response.getEntity().toString(); //String outs = response.getEntity().toString();
String outs = EntityUtils.toString(response.getEntity()); String outs = EntityUtils.toString(response.getEntity());
return outs; return outs;

31
src/main/java/cn/chjyj/szwh/utils/SzFileUtils.java

@ -1,6 +1,9 @@
package cn.chjyj.szwh.utils; package cn.chjyj.szwh.utils;
import cn.chjyj.szwh.configure.EnvConfig; 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.io.*;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
@ -11,6 +14,7 @@ import java.util.Calendar;
* xy * xy
*/ */
public class SzFileUtils { public class SzFileUtils {
private static Log logger = LogFactory.getLog(SzFileUtils.class);
/** /**
* 读取pem文件信息内容,并返回字符串 * 读取pem文件信息内容,并返回字符串
* *
@ -81,18 +85,23 @@ public class SzFileUtils {
String path= EnvConfig.yxDbConf()+File.separator+folder+filename+".json"; String path= EnvConfig.yxDbConf()+File.separator+folder+filename+".json";
File fdFile = new File(folder); File fdFile = new File(folder);
// 检查目录是否存在 // 检查目录是否存在
if(!fdFile.exists()){ if(!fdFile.isDirectory() && !fdFile.exists()){
fdFile.mkdirs(); fdFile.mkdirs();
} }
int index; int index;
byte[] bytes = new byte[1024]; byte[] bytes = new byte[1024];
try { try {
FileOutputStream jsonFile = new FileOutputStream(path); // append 追加到当前文件
while ((index = inputStream.read(bytes)) != -1) { FileOutputStream jsonFile = new FileOutputStream(path,true);
jsonFile.write(bytes, 0, index); if(inputStream.available()>0){
jsonFile.flush(); while ((index = inputStream.read(bytes)) != -1) {
jsonFile.write(bytes, 0, index);
jsonFile.write("\r\n".getBytes());
jsonFile.flush();
}
} }
jsonFile.close(); jsonFile.close();
logger.info("inputstream size :"+inputStream.available());
inputStream.close(); inputStream.close();
}catch (Exception ex){ }catch (Exception ex){
ex.printStackTrace(); ex.printStackTrace();
@ -115,8 +124,18 @@ public class SzFileUtils {
try { try {
InputStream ins = new FileInputStream(fdFile); InputStream ins = new FileInputStream(fdFile);
BufferedReader br = new BufferedReader(new InputStreamReader(ins)); BufferedReader br = new BufferedReader(new InputStreamReader(ins));
String readLine = null; String lineStr = "";
StringBuffer sb = new StringBuffer(); 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(); return sb.toString();
}catch (Exception ex){ }catch (Exception ex){
ex.printStackTrace(); ex.printStackTrace();

6
urls.md

@ -29,3 +29,9 @@
13. [SpringBoot+Quartz+数据库存储+Quartz四大应用场景](https://blog.csdn.net/Lzxccas/article/details/110561320) 13. [SpringBoot+Quartz+数据库存储+Quartz四大应用场景](https://blog.csdn.net/Lzxccas/article/details/110561320)
14. [SpringBoot自动配置Quartz](https://www.shouxicto.com/article/2060.html) 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)
Loading…
Cancel
Save