httpclient模拟浏览器调用服务接口

用httpclient调用服务接口获取数据返回403,并标记为疑似黑客攻击。返回错误结果如果图:

这里写图片描述
这里写图片描述
后发现在httpclient需要把User-Agent设置为浏览器方式:
String userAgent = “Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36”;
httpPost.setHeader(“User-Agent”, userAgent);
完整代码如下:

/**
 * Http客户端管理器
 * @author Tiger
 *
 */
public class HttpConnectionManager {

    private static int SOCKET_TIMEOUT = 30000; //socket超时时间
    private static int CONNECTION_TIMEOUT = 30000;  //连接超时

    private static SSLConnectionSocketFactory socketFactory = null; //私密链接工厂

    private static RequestConfig defaultRequestconfig = null;

    private static RequestConfig requestConfig = null;

    private static Registry<ConnectionSocketFactory> socketFactoryRegistry = null;

    private static TrustManager manager = new X509TrustManager() {

        @Override
        public X509Certificate[] getAcceptedIssuers() { return null; }

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { }

        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { }
    };

    static{

        //SSL套字节
        try {
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new TrustManager[]{manager}, null);
            socketFactory = new SSLConnectionSocketFactory(context,NoopHostnameVerifier.INSTANCE);
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
        }

        //加密链接工厂创建
        socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http",PlainConnectionSocketFactory.INSTANCE).register("https",socketFactory).build();

        //请求配置
        defaultRequestconfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).setExpectContinueEnabled(true)
                .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM,AuthSchemes.DIGEST))
                .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).setSocketTimeout(SOCKET_TIMEOUT).setConnectTimeout(CONNECTION_TIMEOUT).build();

        requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIMEOUT).setConnectTimeout(CONNECTION_TIMEOUT).build();

    }



    /**
     * 执行POST请求
     *
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public static HttpResult post(String url,JSONObject params) throws Exception {

        // 创建POST 请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        if(params.containsKey("sign")){
            httpPost.addHeader("sign", params.getString("sign"));
        }
        // 将请求实体设置到httpPost对象中
        httpPost.setEntity(getFormEntity(params));

        return getHttpResult(url,httpPost);
    }

    /**
     * 执行POST请求
     *
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public static HttpResult postForJSON(String url,JSONObject params) throws Exception {

        // 创建POST 请求
        HttpPost httpPost = new HttpPost(url);
        String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36";
        httpPost.setHeader("User-Agent", userAgent);
        httpPost.setConfig(requestConfig);
        //放入JSON数据
        StringEntity entity = new StringEntity(params.toJSONString());
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        return getHttpResult(url,httpPost);
    }



    /**
     * 执行GET请求
     *
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public static HttpResult get(String url,JSONObject params) throws Exception {

        // 创建POST 请求
        url += formatGETParam(params);
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);
        return getHttpResult(url,httpGet);
    }


    /**
     * 执行PUT请求
     *
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public static HttpResult putForJSON(String url,JSONObject params) throws Exception {

        // 创建POST 请求
        HttpPut httpPut = new HttpPut(url);
        httpPut.setConfig(requestConfig);
        //放入JSON数据
        StringEntity entity = new StringEntity(params.toJSONString());
        entity.setContentType("application/json");
        httpPut.setEntity(entity);
        return getHttpResult(url,httpPut);
    }


    /**
     * 获取HttpClient
     * @param isSSL 是否为https
     * @return
     */
    public static CloseableHttpClient getHttpClient(boolean isSSL){

        // 创建http POST请求
        CloseableHttpClient httpClient = null;
        if(isSSL){
            //链接管理器创建
            PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            httpClient = HttpClients.custom().setConnectionManager(connectionManager).setDefaultRequestConfig(defaultRequestconfig).build();
        }else{
            httpClient = HttpClients.createDefault();
        }

        return httpClient;
    }

    /**
     * 获取UrlEncodedFormEntity
     * @param params
     * @return
     * @throws Exception
     */
    public static UrlEncodedFormEntity getFormEntity(JSONObject params) throws Exception {
        // 设置post参数
        List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
        Set<String> keys = params.keySet();
        Iterator<String> it = keys.iterator();
        while(it.hasNext()){
            String fieldName = it.next();
            String value = params.getString(fieldName);
            if(value != null) {
                parameters.add(new BasicNameValuePair(fieldName, value));
            }
        }
        // 构造一个form表单式的实体
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
        return formEntity;
    }


    /**
     * 获取UrlEncodedFormEntity
     * @param params
     * @return
     * @throws Exception
     */
    public static String formatGETParam(JSONObject params) throws Exception {
        // 设置post参数
        String urlParam = "?";
        Set<String> keys = params.keySet();
        Iterator<String> it = keys.iterator();
        while(it.hasNext()){
            String fieldName = it.next();
            String value = params.getString(fieldName);
            if(value != null) {
                urlParam += fieldName+"="+value+"&";
            }
        }
        urlParam = urlParam.equals("?") ? "" : urlParam.substring(0,urlParam.lastIndexOf("&"));
        return urlParam;
    }





    /**
     * 获取HttpResult
     * @param url
     * @param method
     * @return
     * @throws Exception
     */
    public static HttpResult getHttpResult(String url,HttpUriRequest method) throws Exception{

        // 处理返回
        HttpResult httpResult;
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            httpClient = getHttpClient(url.contains("https"));  // 创建请求客户端
            System.out.println(method);
            response = httpClient.execute(method);              // 执行请求
            httpResult = new HttpResult(response.getStatusLine().getStatusCode(),EntityUtils.toString(response.getEntity(),"UTF-8"));
        } catch (Exception e){
            e.printStackTrace();
            httpResult = new HttpResult(500,e.getMessage());
        } finally {
            if (response != null) {
                response.close();
            }
            if(httpClient != null){
                httpClient.close();
            }
        }
        System.out.println(httpResult);
        return httpResult;
    }





}

猜你喜欢

转载自blog.csdn.net/maying0124/article/details/80913516
今日推荐