1.工具包依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.74</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.30</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.10</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
2.logback日志配置(logback.xml)
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<property name="LOG_HOME" value="c:/log" />
<!-- 控制台输出 -->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
</pattern>
</layout>
</appender>
<!-- 按照每天生成日志文件 -->
<appender name="FILE"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${LOG_HOME}/myApp.log.%d{yyyy-MM-dd}.log</FileNamePattern>
<MaxHistory>30</MaxHistory>
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
</pattern>
</layout>
</appender>
<root level="DEBUG">
<appender-ref ref="CONSOLE" />
<!-- <appender-ref ref="FILE" />-->
</root>
</configuration>
说明: 将logback.xml放到resources/下
3.http工具类
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class HttpUtil {
static volatile int count = 0;
public static String sendGet(String url) {
String result = "";
InputStream inputStream = null;
BufferedReader bufferedReader = null;
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
URI uri = new URI(url);
HttpGet httpGet = new HttpGet(uri);
response = client.execute(httpGet);
URI testUri = httpGet.getURI();
Header[] headers = response.getAllHeaders();
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// 包装输入流
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuffer sbf = new StringBuffer();
// 读取封装的输入流
String temp = null;
while ((temp = bufferedReader.readLine()) != null) {
sbf.append(temp).append("\r\n");
}
result = sbf.toString();
return result;
} catch (URISyntaxException | IOException e) {
e.printStackTrace();
} finally{
// 关闭资源
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != inputStream) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null != response) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
// json数据请求
public static String sendPostByJson(String requestUrl,String json){
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(requestUrl);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(10000)
.setConnectionRequestTimeout(10000)
.setSocketTimeout(10000)
.build();
httpPost.setConfig(requestConfig);
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");//表示客户端发送给服务器端的数据格式
//httpPost.setHeader("Accept", "*/*");这样也ok,只不过服务端返回的数据不一定为json
httpPost.setHeader("Accept", "application/json"); //表示服务端接口要返回给客户端的数据格式,
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
try{
CloseableHttpResponse response = httpclient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
//System.out.println(EntityUtils.toString(response.getEntity(), "UTF-8"));
System.out.println(statusCode);//200
if (statusCode == HttpStatus.SC_OK) {
HttpEntity respEnt = response.getEntity();
respHtml = EntityUtils.toString(respEnt, "UTF-8");
JSONObject jsonObject = JSONObject.parseObject(respHtml);//响应结果
return jsonObject.toJSONString();
}
}catch (Exception e){
}
JSONObject jsonObject = new JSONObject();
jsonObject.put("res","");
return jsonObject.toJSONString();
}
}
至此,常用的工具依赖及配置就结束了,之后发现其它好用的东西会持续更新!!