美文网首页
基于apache HttpClient工具类

基于apache HttpClient工具类

作者: 离别刀 | 来源:发表于2018-06-11 15:35 被阅读0次
    1153958.png

    依赖jar包

    <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.2</version>
    </dependency>
    <dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.4</version>
    </dependency>
    <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.17</version>
    </dependency>

    工具类HttpClientService

    import com.alibaba.fastjson.JSON;
    import org.apache.commons.lang3.StringUtils;
    import org.apache.http.Header;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.config.RequestConfig;
    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.client.methods.HttpPost;
    import org.apache.http.client.utils.URIBuilder;
    import org.apache.http.entity.ContentType;
    import org.apache.http.entity.StringEntity;
    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.springframework.stereotype.Service;
    
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    
    @Service
    public class HttpClientService {
        private static RequestConfig requestConfig;
        static {
            requestConfig = RequestConfig.custom()
                    .setSocketTimeout(2000)
                    .setConnectionRequestTimeout(2000)
                    .setConnectTimeout(2000).build();
        }
    
        public static String doGet(String url,Map<String,String> params,Header header){
            return doGetDetail(url,null,header);
        }
    
        public static  <T> T doGet(String url,Map<String,String> params,Header header,Class<T> clazz){
            return JSON.parseObject(doGetDetail(url,params,header),clazz);
        }
    
        public static String doPost(String url,Header header){
            return doPostJSONDetail(url,null,header);
        }
    
        public static String doPostJSON(String url,Object object,Header header){
            return doPostJSONDetail(url,JSON.toJSONString(object),header);
        }
    
        public static <T> T doPostJSON(String url,Object object,Header header,Class<T> clazz){
            return JSON.parseObject(doPostJSONDetail(url,JSON.toJSONString(object),header),clazz);
        }
    
        public static <T> T doPostJSON(String url,String json,Header header,Class<T> clazz){
            return JSON.parseObject(doPostJSONDetail(url,json,header),clazz);
        }
    
        public static String doPostForm(String url,Map<String,String> params,Header header){
            return doPostFormDetail(url,params,header);
        }
    
        public static <T> T doPostForm(String url,Map<String,String> params,Header header,Class<T> clazz){
            return JSON.parseObject(doPostFormDetail(url,params,header),clazz);
        }
    
        private static String doGetDetail(String url,Map<String,String> params,Header header){
            String rest= "";
            CloseableHttpResponse response = null;
            CloseableHttpClient httpClient = HttpClients.createDefault();
            try{
                URIBuilder uriBuilder= new URIBuilder(url);
                if(params!=null){
                    Set<String> keys= params.keySet();
                    for(String key:keys){
                        uriBuilder.addParameter(key,params.get(key));
                    }
                }
                HttpGet httpGet= new HttpGet(uriBuilder.build());
                if(header!=null){
                    httpGet.setHeader(header);
                }
                httpGet.setConfig(requestConfig);
                response= httpClient.execute(httpGet);
                if(response.getStatusLine().getStatusCode()==200){
                    rest= EntityUtils.toString(response.getEntity(),"UTF-8");
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                try {
                    if (response != null) {
                        response.close();
                    }
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return rest;
        }
    
        private static String doPostJSONDetail(String url,String json,Header header){
            String rest= "";
            CloseableHttpResponse response = null;
            CloseableHttpClient httpClient = HttpClients.createDefault();;
            try{
                HttpPost httpPost= new HttpPost(url);
                if(header!=null){
                    httpPost.setHeader(header);
                }
                if(StringUtils.isNotEmpty(json)){
                    StringEntity entity= new StringEntity(json, ContentType.APPLICATION_JSON);
                    httpPost.setEntity(entity);
                }
                response= httpClient.execute(httpPost);
                if(response.getStatusLine().getStatusCode()==200){
                    rest= EntityUtils.toString(response.getEntity(),"UTF-8");
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                try {
                    if (response != null) {
                        response.close();
                    }
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return rest;
        }
    
    
        private static String doPostFormDetail(String url,Map<String,String> params,Header header){
            CloseableHttpClient httpClient = HttpClients.createDefault();;
            String rest= "";
            CloseableHttpResponse response = null;
            try{
                HttpPost httpPost= new HttpPost(url);
                if(header!=null){
                    httpPost.setHeader(header);
                }
                if(params!=null){
                    List<NameValuePair> nameValuePairs= new ArrayList<>();
                    Set<String> keys= params.keySet();
                    for(String key:keys){
                        nameValuePairs.add(new BasicNameValuePair(key,params.get(key)));
                    }
                    UrlEncodedFormEntity entity= new UrlEncodedFormEntity(nameValuePairs,"UTF-8");
                    httpPost.setEntity(entity);
                }
                response= httpClient.execute(httpPost);
                if(response.getStatusLine().getStatusCode()==200){
                    rest= EntityUtils.toString(response.getEntity(),"UTF-8");
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                try {
                    if (response != null) {
                        response.close();
                    }
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return rest;
        }
    }
    

    测试类HttpClientCtrl

    import com.example.demo.util.HttpClientService;
    import org.apache.http.Header;
    import org.apache.http.message.BasicHeader;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.HashMap;
    import java.util.Map;
    
    @RequestMapping("/hct")
    @RestController
    public class HttpClientCtrl {
    
        @RequestMapping(value = "/get",method = RequestMethod.GET)
        public Object doGet(){
            Map<String,String> params= new HashMap<>();
            params.put("name","ligang");
            params.put("age","10");
            Header header= new BasicHeader("","");
            String rest= HttpClientService.doGet("http://localhost:9999/hct/get1",params,header);
            return rest;
        }
    
        @RequestMapping(value = "/get1",method = RequestMethod.GET)
        public User doGet1(){
            User user= new User();
            user.age= "20";
            user.name= "xiaoli";
            return user;
        }
    
        public static class User{
            public String name;
            public String age;
        }
    }
    

    运行结果:
    {"name":"xiaoli","age":"20"}

    @Service
    public class RestTemplateService {
    
        private static final Logger logger= LoggerFactory.getLogger(RestTemplateService.class);
        @Autowired
        private RestTemplate restTemplate;
    
    
        public <T> T postForApplicationJson(String url, Map<String, Object> params, Class<T> type){
            Long loginIndex= System.currentTimeMillis();
            logger.info("[loginIndex:{}] request for:{},params:{}", loginIndex, url, JSON.toJSONString(params));
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            HttpEntity<Map<String, Object>> request = new HttpEntity<Map<String, Object>>(params, headers);
            try {
                ResponseEntity<T> responseEntity= restTemplate.postForEntity(url, request, type);
                return responseEntity.getBody();
            }catch (Exception e){
                logger.info("[loginIndex:{}] request for:{}",loginIndex,url, e);
            }
            return null;
        }
    }
    

    相关文章

      网友评论

          本文标题:基于apache HttpClient工具类

          本文链接:https://www.haomeiwen.com/subject/medheftx.html