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

Posted sitian2050

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了对HttpClient实现的 HTTP 方法中getpost有无参数方法抽取一个公共类相关的知识,希望对你有一定的参考价值。

/**
 * 抽取一个公共的类
 * 
 * @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 方法中getpost有无参数方法抽取一个公共类的主要内容,如果未能解决你的问题,请参考以下文章

java实现HTTP请求的三种方式

java实现HTTP请求的三种方式

JAVA通过HttpClient发送HTTP请求的方法

HttpClient来自官方的JSON扩展方法

HttpComponents HttpClient连接池-结构

转Java模拟http请求,调用外部api接口:HttpURLConnection和HttpClient的区别