天天看点

HttpClient get请求调取接口 例子

package com.xiaojukeji.service.impl;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;

import org.apache.http.Consts;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.xiaojukeji.common.log.LogMessage;
import com.xiaojukeji.dao.mapper.RegionMapper;
import com.xiaojukeji.service.RegionService;

/** 
 * Description: [区域服务实现]
 * Created on 2017年11月13日
 * @author  <a href="mailto: 1[email protected]" target="_blank" rel="external nofollow" >全冉</a>
 * @version 1.0 
 * Copyright (c) 2017年 全冉公司  
 */
@Component
public class RegionServiceImpl implements RegionService {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(RegionServiceImpl.class);
	
	/**
	 * <p>Discription:[区域Mapper]</p>
	 */	
	@Resource
	private RegionMapper regionMapper;

	/**
	 * <p>Discription:[发送 get请求获取城市或办公区数据]</p>
	 * Created on 2017年11月22日 下午7:30:49
	 * @param id 父级id
	 * @return String get请求得到的json数据
	 * @author:[全冉]
	 */
    public String get(Long id) {  
    	String result = "";
    	CloseableHttpClient httpclient = HttpClients.createDefault();
    	CloseableHttpResponse response = null;
    	try {
			// 封装请求参数  
            List<NameValuePair> paramsList = Lists.newArrayList();  
            paramsList.add(new BasicNameValuePair("id", String.valueOf(id)));
            // 转换为键值对  
            String params = EntityUtils.toString(new UrlEncodedFormEntity(paramsList, Consts.UTF_8));
            // 请求地址
    		String uri = "http://10.97.136.138/api/ecmdev/area/queryChildAreaListById";
            uri += "?" + params;
	        // 创建httpGet.  
	        HttpGet httpGet = new HttpGet(uri);  
	        // 通过请求对象获取响应对象
	        response = httpclient.execute(httpGet);
	        // 判断网络连接状态码是否正常(0--200都数正常)
	        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
	            result= EntityUtils.toString(response.getEntity(), "utf-8");
	        } 
    	} catch (Exception e) {
    		LOGGER.error(LogMessage.getNew()
					.add("发送 get请求获取城市或办公区数据")
					.add("===入参====", id)
					.add("===错误信息====", e).toString());
			return result;
    	} finally {
    		try {
    			if (response != null) {
    				response.close();
    			}
				httpclient.close(); 
			} catch (IOException e) {
				e.printStackTrace();
			}  
    	}
    	return result;
    }

}
           

继续阅读