[java]代码库
//可能需要引入的倒包
import javax.servlet.http.HttpServletRequest;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
public void CurrentVisitor(){
// 需要访问的接口路径
String act = ServletActionContext.getRequest().getParameter("act");
String limit = ServletActionContext.getRequest().getParameter("limit");
// 需要访问的接口路径
String url = "";
if(act.equals("xinhuawang")){
url = "http://172.17.9.36:8124/"+act+"/visitors?limit="+limit;
}
else{
url = "http://192.168.20.71:8124/"+act+"/visitors?limit="+limit;
System.out.println(url);
}
// 配置请求信息(请求时间)
RequestConfig rc = RequestConfig.custom().setSocketTimeout(60000)
.setConnectTimeout(60000).build();
// 获取使用DefaultHttpClient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
// 返回结果
String result = null;
try {
if (url != null) {
// 创建HttpGet对象,将URL通过构造方法传入HttpGet对象
HttpGet httpget = new HttpGet(url);
// 将配置好请求信息附加到http请求中
httpget.setConfig(rc);
// 执行DefaultHttpClient对象的execute方法发送GET请求,通过CloseableHttpResponse接口的实例,可以获取服务器返回的信息
CloseableHttpResponse response = httpclient.execute(httpget);
try {
// 得到返回对象
HttpEntity entity = response.getEntity();
if (entity != null) {
// 获取返回结果
result = EntityUtils.toString(entity);
}
} finally {
// 关闭到客户端的连接
response.close();
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭http请求
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
CommonUtil.printAjaxResult(result);
}
[源代码打包下载]
by: 发表于:2017-06-21 17:23:04 顶(0) | 踩(0) 回复
??
回复评论