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

/**
 * 抽取一个公共的类
 *
 * @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;
        }

}

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

时间: 2024-08-04 14:31:10

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

java继承-子类调用父类的方法中包含子类重写的方法

# 看题目是不是很绕,这个我也不知道怎么才能更简单的表达了... # 先看代码: public class Common { public static void main(String[] args) { Sub sub = new Sub(); sub.testSub(); } } class Parent { protected boolean test() { throw new RuntimeException(); } protected void testParent() { if

SpringMVC 中,当前台传入多个参数时,可将参数封装成一个bean类

在实际业务场景中,当前台通过 url 向后台传送多个参数时,可以将参数封装成一个bean类,在bean类中对各个参数进行非空,默认值等的设置. 前台 url ,想后台传送两个参数,userName 和 password: 1 http://localhost:8082/web/baseAction.do?pathVar=app/task/fetchItemDetail.do?userName=123&password=123 将参数封装成bean 类,并在bean类中对参数进行控制: 1 2 3

如果给JQ的ajax方法中的success()传入参数?

当时在使用JQuery提供的Ajax技术的时候,我有个需求,就是要给它请求成功后调用的success()方法传入参数: 所以,我就直接这样子写了: <script> function getTypeList(name){ $.ajax({ url : '<c:url value="admin/type_loadTypeList.action"/>', type : 'get', contentType : "text/html;charset=utf-

ASP.NET中常用的几个李天平开源公共类LTP.Common,Maticsoft.DBUtility,LtpPageControl

ASP.NET中常用的几个开源公共类: LTP.Common.dll: 通用函数类库     源码下载Maticsoft.DBUtility.dll 数据访问类库组件     源码下载LtpPageControl.dll    Web分页控件   源码下载 本博客下载地址: LTP.Common.dll: 通用函数类库     源码下载Maticsoft.DBUtility.dll 数据访问类库组件     源码下载LtpPageControl.dll    Web分页控件   源码下载 来自:

String在方法中的传递方式(调用外部方法给String变量赋值时,未得到预期结果)

示例: public class StringTraining { public static void changeStr(String str){ str = "137878"; } public static void main(String[] args){ String a = "b"; changeStr(a); System.out.println(a); }} 输出仍旧为b 分析:首先栈中存的是堆中对象的地址,因为String对象的特殊性(Strin

__getattribute__(self, obj) 这个方法中的obj这个参数

class Itcast(object): def __init__(self, subject1): self.subject1 = subject1 print("^^^^^^^-------%s" %self.subject1) self.subject2 = 'cpp' def __getattribute__(self, obj): print("===========1============") print("-------%s"

angularjs 中传递非URL参数方法

在目标页面规定接受的参数:$stateProvider.state('page2', {params: {'DATA': null}}) 传参:$state.go('page2', {DATA: 'aaa'}); 目标页面接受参数:控制器注入$stateParams之后可以通过$stateParams.DATA来获取‘aaa’

react父子组件通讯-----&gt;下面用到的ref属性调用子组件的方法,可以实现子组件往父组件传递参数,可以通过在父组件的方法中调用子组件的方法,通过返回值来拿到值,也可以在子组件中,对数据处理完后,调用父组件传给子组件的参数或者方法,来实现传参,

<scripttype="text/babel"> var Child =React.createClass({ getInitialState: function() { return {color:"",childMsg:"我是子组件的信息"}; }, changeColor: function(e) { this.setState({color:e.target.getAttribute("data-color&quo

idea java方法中 传多个参数对象 的复制粘贴快速处理方法

比如像这种的传多个参数对象,我是直接复制过来,然后把第一个字母改成大写,然后后面的实例对象敲一个第一个字符的小写就直接出来了 原文地址:https://www.cnblogs.com/kinome/p/10314670.html