第一步:在POM.xml中添加dependency
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore-nio</artifactId>
<scope>compile</scope>
</dependency>
第二步:
package com.beichenyashi.apps.mgr.printagent.service.impl;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.beichenyashi.apps.mgr.printagent.service.IHttpClientTaskService;
/**
* HttpClient 查询 服务器的信息
* @author jiangxingqi
*
*/
@Service
public class HttpClientTaskServiceImpl implements IHttpClientTaskService {
private final static Logger LOGGER = LoggerFactory
.getLogger(HttpClientTaskServiceImpl.class);
/**
* 通过httpClient 轮询获取 最早请求打印任务所对应的 judgeID
*/
@Override
public String getBlockedPrintTaskJudgeId(String ip, int port,String contextPath) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String url = "http://"+ ip +":"+ port + contextPath + "/common/blocked/task/usedcar/judge/id";
// 创建httpGet
HttpGet httpGet = new HttpGet(url);
// 执行get请求.
CloseableHttpResponse response = null;
//机动车检验记录表的id
String id=null;
try {
response = httpClient.execute(httpGet);
// 获取响应实体
org.apache.http.HttpEntity entity = response.getEntity();
if (entity != null) {
id = EntityUtils.toString((org.apache.http.HttpEntity) entity);
}
} catch (ClientProtocolException e) {
LOGGER.error("url:{} 异常:", url, e);
} catch (IOException e) {
LOGGER.error("url:{} 异常:", url, e);
} finally{
//关闭response
if(null != response){
try {
response.close();
} catch (IOException e) {
LOGGER.error("url:{} 异常:", url, e);
}
}
//关闭httpClient
try {
httpClient.close();
} catch (IOException e) {
LOGGER.error("url:{} 异常:", url, e);
}
}
return id;
}
}