基于apache HttpClient工具类

基于apache HttpClient工具类_第1张图片
1153958.png

依赖jar包


org.apache.httpcomponents
httpclient
4.5.2


org.apache.commons
commons-lang3
3.4


com.alibaba
fastjson
1.2.17

工具类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 params,Header header){
        return doGetDetail(url,null,header);
    }

    public static   T doGet(String url,Map params,Header header,Class 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 doPostJSON(String url,Object object,Header header,Class clazz){
        return JSON.parseObject(doPostJSONDetail(url,JSON.toJSONString(object),header),clazz);
    }

    public static  T doPostJSON(String url,String json,Header header,Class clazz){
        return JSON.parseObject(doPostJSONDetail(url,json,header),clazz);
    }

    public static String doPostForm(String url,Map params,Header header){
        return doPostFormDetail(url,params,header);
    }

    public static  T doPostForm(String url,Map params,Header header,Class clazz){
        return JSON.parseObject(doPostFormDetail(url,params,header),clazz);
    }

    private static String doGetDetail(String url,Map params,Header header){
        String rest= "";
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try{
            URIBuilder uriBuilder= new URIBuilder(url);
            if(params!=null){
                Set 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 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 nameValuePairs= new ArrayList<>();
                Set 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 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 postForApplicationJson(String url, Map params, Class 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> request = new HttpEntity>(params, headers);
        try {
            ResponseEntity responseEntity= restTemplate.postForEntity(url, request, type);
            return responseEntity.getBody();
        }catch (Exception e){
            logger.info("[loginIndex:{}] request for:{}",loginIndex,url, e);
        }
        return null;
    }
}

你可能感兴趣的:(基于apache HttpClient工具类)