码迷,mamicode.com
首页 > Web开发 > 详细

对HttpClient实现的 HTTP 方法中get、post有无参数方法抽取一个公共类

时间:2019-10-19 20:55:25      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:exce   private   get请求   import   key   auth   ble   set   data   

/**
 * 抽取一个公共的类
 * 
 * @author xz
 *
 */
@Service
public class ApiService {
    @Autowired
    private RequestConfig config;
    @Autowired
    private CloseableHttpClient httpClient;

    /**
     * 无参的get请求
     * 
     * @param url
     * @return
     */
    public String doGet(String url) {
        // HttpGet对象
        HttpGet get = new HttpGet(url);
        get.setConfig(config);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(get);
            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity(), "utf-8");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 有参的get请求
     * 
     * @param url
     * @return
     */
    public String doGet(String url, Map<String, Object> params) {
        List<NameValuePair> nvprs = new ArrayList<>();
        // 遍历map
        for (String key : params.keySet()) {
            NameValuePair nvpr = new BasicNameValuePair(key, params.get(key).toString());
            nvprs.add(nvpr);
        }
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(url).addParameters(nvprs).build();
            // HttpGet对象
            HttpGet get = new HttpGet(uri);
            get.setConfig(config);
            response = httpClient.execute(get);
            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity(), "utf-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    // Save Update Delete (状态不同 返回值不一样? 有的有返回值 有的没有返回值。)
    public Result doPost(String url, Map<String, Object> params) {
        List<NameValuePair> nvprs = new ArrayList<>();
        // 遍历map
        for (String key : params.keySet()) {
            NameValuePair nvpr = new BasicNameValuePair(key, params.get(key).toString());
            nvprs.add(nvpr);
        }
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(url).addParameters(nvprs).build();
            // HttpGet对象
            HttpPost post = new HttpPost(uri);
            post.setConfig(config);
            response = httpClient.execute(post);
            return new Result(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(response.getEntity(), "utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    // Save Update Delete (状态不同 返回值不一样? 有的有返回值 有的没有返回值。)
    public Result doPost(String url) {
        CloseableHttpResponse response = null;
        try {
            // HttpGet对象
            HttpPost post = new HttpPost(url);
            post.setConfig(config);
            response = httpClient.execute(post);
            return new Result(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(response.getEntity(), "utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}

对以上方法应用的示例

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.taotao.manage.pojo.Item;

@Service
public class ItemService {
        @Autowired
        private ApiService apiService;
        private ObjectMapper mapper=new ObjectMapper();
        
        public Item iteminfo(Long itemId) {
            Map<String,Object> params=new HashMap<String,Object>();
            params.put("itemId", itemId);
            String data=apiService.doGet("http://manage.taotao.com/rest/item/queryId",params);
            System.out.println(data);
            if(StringUtils.isNotBlank(data)) {
                try {
                    //当封装实体类时
                    Item item=mapper.readValue(data,Item.class);
                    return item;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            return null;
        }
        
}

 

对HttpClient实现的 HTTP 方法中get、post有无参数方法抽取一个公共类

标签:exce   private   get请求   import   key   auth   ble   set   data   

原文地址:https://www.cnblogs.com/sitian2050/p/11704980.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!