简单的eHttpClient工具类

简单的eHttpClient工具类
强烈推介IDEA2020.2破解激活,IntelliJ IDEA 注册码,2020.2 IDEA 激活码
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 简单的eHttpClient工具类
 *
 * Created by chao on 2017/6/27. */
public class SimpleHttpClientUtil {

    private Logger logger = LoggerFactory.getLogger(getClass()) ;
    private HttpClient httpClient ;
    private HttpClientContext httpClientContext ;

    /**
     * 无参空构造
     */
    public SimpleHttpClientUtil(){}

    /**
     * 含参构造
     * @param client httpClient
     * @param context HttpClientContext
     */
    public SimpleHttpClientUtil(HttpClient client, HttpClientContext context){
        this.httpClient = httpClient ;
        this.httpClientContext = httpClientContext ;
    }

    /**
     * 重定向
     * @param response 重定向上游HttpResponse
     * @param client HttpClient
     * @param context HttpClientContext
     * @return HttpResponse
     */
    public HttpResponse redirectResp(HttpResponse response, HttpClient client, HttpClientContext context){
        Header header=response.getFirstHeader("Location") ;
        return httpGetResp(client,context,header.getValue()) ;
    }

    /**
     * 重定向
     * @param response 重定向上游HttpResponse
     * @param client HttpClient
     * @param context HttpClientContext
     * @return 响应码
     */
    public int redirect(HttpResponse response, HttpClient client, HttpClientContext context){
        Header header=response.getFirstHeader("Location") ;
        return httpGet(client,context,header.getValue()) ;
    }

    public int redirect(HttpResponse response){
        return redirect(response,this.httpClient,this.httpClientContext) ;
    }

    /**
     * GET 方式访问
     *
     * @param client HttpClient
     * @param context HttpClientContext
     * @param url url
     * @return 响应文本内容
     */
    public String httpGetRespTxt(HttpClient client, HttpClientContext context,String url){
        String webTxt ;
        HttpGet httpGet = new HttpGet(url) ;
        HttpResponse response ;
        httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240") ;//逃避反爬虫
        try{
            response = client.execute(httpGet,context) ;
            webTxt = EntityUtils.toString(response.getEntity()) ;
        }catch (Exception e){
            logger.error("GET 方式访问异常:"+url,e) ;
            throw new SimpleException(2,"Http响应:"+e.getMessage()) ;
        }finally {
            httpGet.abort() ;
        }
        return webTxt ;
    }

    /**
     * GET 方式访问
     *
     * @param client HttpClient
     * @param context HttpClientContext
     * @param url url
     * @return HttpResponse
     */
    public HttpResponse httpGetResp(HttpClient client, HttpClientContext context,String url){
        HttpGet httpGet = new HttpGet(url) ;
        HttpResponse response ;
        httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240") ;//逃避反爬虫
        try{
            response = client.execute(httpGet,context) ;
        }catch (Exception e){
            logger.error("GET 方式访问异常:"+url,e) ;
            throw new SimpleException(2,"Http响应:"+e.getMessage()) ;
        }finally {
            httpGet.abort() ;
        }
        return response ;
    }

    /**
     * GET 方式访问
     *
     * @param client HttpClient
     * @param context HttpClientContext
     * @param url url
     * @return 响应码
     */
    public int httpGet(HttpClient client, HttpClientContext context,String url){
        return httpGetResp(client,context,url).getStatusLine().getStatusCode() ;
    }

    /**
     * GET 方式访问
     * @param url url
     * @return 响应码
     */
    public int httpGet(String url) {
        return httpGet(this.httpClient,this.httpClientContext,url) ;
    }

    /**
     * post json请求
     * @param client HttpClient
     * @param context HttpClientContext
     * @param url url
     * @param json json
     * @return json
     */
    public String httpPostJson(HttpClient client, HttpClientContext context,String url,String json){
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36") ;//逃避反爬虫
        String resultJson="" ;
        HttpResponse httpResponse = null ;
        try {
            StringEntity se = new StringEntity(json);
            se.setContentEncoding("UTF-8");
            se.setContentType("application/json");//发送json数据需要设置contentType
            httpPost.setEntity(se);
            httpResponse = client.execute(httpPost);
            if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                resultJson= EntityUtils.toString(httpResponse.getEntity());// 返回json格式:
            }
        } catch (Exception e) {
            System.out.println("httpPostJson:"+httpResponse.getStatusLine());
            logger.error("POST 方式访问异常:"+url+" httpPostJson:"+httpResponse.getStatusLine(),e) ;
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return resultJson ;
    }
    /**
     * POST 方式访问
     * @param client HttpClient
     * @param context HttpClientContext
     * @param url url
     * @param nvp List<NameValuePair>
     * @return 响应文本内容
     */
    public String httpPostRespTxt(HttpClient client, HttpClientContext context,String url,List<NameValuePair> nvp){
        String webTxt;
        HttpPost httpPost = new HttpPost(url) ;
        httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36") ;//逃避反爬虫
        HttpResponse response ;
        try{
            httpPost.setEntity(new UrlEncodedFormEntity(nvp,"UTF-8")) ;
            response = client.execute(httpPost,context) ;
            webTxt = EntityUtils.toString(response.getEntity()) ;
        }catch (Exception e){
            logger.error("POST 方式访问异常:"+url,e) ;
            throw new SimpleException(2,"Http响应:"+e.getMessage()) ;
        }finally {
            httpPost.abort() ;
        }
        return webTxt ;
    }

    /**
     * POST 方式访问
     * @param client HttpClient
     * @param context HttpClientContext
     * @param url url
     * @param nvp List<NameValuePair>
     * @return HttpResponse
     */
    public HttpResponse httpPostResp(HttpClient client, HttpClientContext context,String url,List<NameValuePair> nvp){
        HttpPost httpPost = new HttpPost(url) ;
        httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36") ;//逃避反爬虫
        HttpResponse response ;
        try{
            httpPost.setEntity(new UrlEncodedFormEntity(nvp,"UTF-8")) ;
            response = client.execute(httpPost,context) ;
        }catch (Exception e){
            logger.error("POST 方式访问异常:"+url,e) ;
            throw new SimpleException(2,"Http响应:"+e.getMessage()) ;
        }finally {
            httpPost.abort() ;
        }
        return response ;
    }
    /**
     * POST 方式访问
     * @param client HttpClient
     * @param context HttpClientContext
     * @param url url
     * @param nvp List<NameValuePair>
     * @return 响应码
     */
    public int httpPost(HttpClient client, HttpClientContext context,String url,List<NameValuePair> nvp){
        return httpPostResp(client,context,url,nvp).getStatusLine().getStatusCode() ;
    }

    /**
     * POST 方式访问
     * @param url url
     * @param nvp List<NameValuePair>
     * @return 响应码
     */
    public int httpPost(String url,List<NameValuePair> nvp){
        return httpPost(this.httpClient,this.httpClientContext,url,nvp) ;
    }
}
<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.2</version>
        </dependency>
本文来源水边风,由架构君转载发布,观点不代表Java架构师必看的立场,转载请标明来源出处:https://javajgs.com/archives/16358

发表评论