2020年4月10日 星期五

Maven Get Html Content use HttpPost

//url: target url address
//id: post include params 
private static String getHtmlContent(String url, String id) throws IOException {
System.setProperty("javax.net.debug","ssl,handshake");
System.setProperty("sun.security.ssl.allowUnsafeRenegotiation","true");
String content = "";
try {   
                   //if use https or call https url addr than show handshake failed return, can add in pass check
SSLContext sslcontext = SSLContexts.createDefault();
SSLConnectionSocketFactory sslsf = new 
              SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1.2"}, null, new NoopHostnameVerifier());
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        
        try {        
    //Use HttpGet method 
    //HttpGet webGet = new HttpGet(url);
                            //Use HttpPost method 
    HttpPost webGet = new HttpPost(url); 
    ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>( );
    params.add(new BasicNameValuePair("id" ,id )) ;
    webGet.setEntity(new UrlEncodedFormEntity(params));
    
    CloseableHttpResponse response = httpClient.execute(webGet);
    HttpEntity entity = response.getEntity();
    content = EntityUtils.toString(entity, "UTF-8");
    content = content.replace("&emsp;", "<font color='white'>_</font>");
    //System.out.println(content);
    EntityUtils.consume(entity);
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
} finally {
httpClient.close();
}         
} catch (Exception ex) {
log.error("createIgnoreVerifySSL has exception " + ex.getMessage(), ex);
}
    return content;
}  


沒有留言: