前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >通过 HttpClient 从指定服务器获取数据

通过 HttpClient 从指定服务器获取数据

作者头像
week
发布2018-08-27 09:33:33
2.1K0
发布2018-08-27 09:33:33
举报
文章被收录于专栏:用户画像用户画像用户画像

第一步:在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;
	}
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015年07月31日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档