使用httpclient 抓包 提交表單 網(wǎng)絡(luò)請求

接了個私活,批量注冊某app賬號,使用fiddler抓包后,多線程批量注冊,httpclient的請求工具類源碼可以通用任何需要網(wǎng)絡(luò)請求的地方,分享出來

package cn.zhaozhiguang.hepai.util;
 
import java.io.File;
import java.io.IOException;  
import java.security.KeyManagementException;  
import java.security.KeyStore;  
import java.security.KeyStoreException;  
import java.security.NoSuchAlgorithmException;  
import java.security.cert.CertificateException;  
import java.security.cert.X509Certificate;  
import java.util.ArrayList;  
import java.util.Iterator;  
import java.util.List;  
import java.util.Map;  
 
import javax.net.ssl.SSLContext;
 
import org.apache.http.*;  
import org.apache.http.client.ClientProtocolException;  
import org.apache.http.client.config.RequestConfig;  
import org.apache.http.client.entity.UrlEncodedFormEntity;  
import org.apache.http.client.methods.*;  
import org.apache.http.config.Registry;  
import org.apache.http.config.RegistryBuilder;  
import org.apache.http.conn.socket.ConnectionSocketFactory;  
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;  
import org.apache.http.conn.socket.PlainConnectionSocketFactory;  
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;  
import org.apache.http.impl.client.HttpClientBuilder;  
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;  
import org.apache.http.message.BasicNameValuePair;  
import org.apache.http.util.EntityUtils;  
import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;  
 
 
@SuppressWarnings("deprecation")
public class HttpUtil {
 
    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);  
    
    private static int SocketTimeout = 30000;//30秒  
    
    private static int ConnectTimeout = 30000;//30秒  
    
    private static Boolean SetTimeOut = true;  
    
    private static CloseableHttpClient getHttpClient() {  
        RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create();  
        ConnectionSocketFactory plainSF = new PlainConnectionSocketFactory();  
        registryBuilder.register("http", plainSF);  
        //指定信任密鑰存儲對象和連接套接字工廠  
        try {  
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());  
            //信任任何鏈接  
            TrustStrategy anyTrustStrategy = new TrustStrategy() {  
                
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {  
                    return true;  
                }  
            };  
            SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, anyTrustStrategy).build();  
            LayeredConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
            registryBuilder.register("https", sslSF);  
        } catch (KeyStoreException e) {  
            throw new RuntimeException(e);  
        } catch (KeyManagementException e) {  
            throw new RuntimeException(e);  
        } catch (NoSuchAlgorithmException e) {  
            throw new RuntimeException(e);  
        }  
        Registry<ConnectionSocketFactory> registry = registryBuilder.build();  
        //設(shè)置連接管理器  
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);  
        //構(gòu)建客戶端  
        return HttpClientBuilder.create().setConnectionManager(connManager).build();  
    }  
  
    /** 
     * get 
     * 
     * @param url     請求的url 
     * @param queries 請求的參數(shù)摩桶,在瀏覽器深员?后面的數(shù)據(jù),沒有可以傳null 
     * @return 
     * @throws IOException 
     */  
    public static String get(String url, Map<String, String> queries) throws IOException {  
        String responseBody = "";  
        CloseableHttpClient httpClient = getHttpClient();  
        StringBuilder sb = new StringBuilder(url);  
        if (queries != null && queries.keySet().size() > 0) {  
            boolean firstFlag = true;  
            Iterator<Map.Entry<String, String>> iterator = queries.entrySet().iterator();  
            while (iterator.hasNext()) {  
                Map.Entry<String, String> entry = iterator.next();  
                if (firstFlag) {  
                    sb.append("?" + (String) entry.getKey() + "=" + (String) entry.getValue());  
                    firstFlag = false;  
                } else {  
                    sb.append("&" + (String) entry.getKey() + "=" + (String) entry.getValue());  
                }  
            }  
        }  
        HttpGet httpGet = new HttpGet(sb.toString());  
        if (SetTimeOut) {  
            RequestConfig requestConfig = RequestConfig.custom()  
                    .setSocketTimeout(SocketTimeout)  
                    .setConnectTimeout(ConnectTimeout).build();//設(shè)置請求和傳輸超時時間  
            httpGet.setConfig(requestConfig);  
        }  
        try {  
            logger.debug("Executing request " + httpGet.getRequestLine());
            //請求數(shù)據(jù)  
            CloseableHttpResponse response = httpClient.execute(httpGet);  
            int status = response.getStatusLine().getStatusCode();  
            if (status == HttpStatus.SC_OK) {  
                HttpEntity entity = response.getEntity();  
                responseBody = EntityUtils.toString(entity);  
                logger.debug(responseBody);
                EntityUtils.consume(entity);  
            } else {  
                logger.debug("http return status error:" + status);
                throw new ClientProtocolException("Unexpected response status: " + status);  
            }  
        } catch (Exception ex) {  
            logger.debug("get請求時發(fā)生錯誤~");
        } finally {  
            httpClient.close();  
        }  
        return responseBody;  
    }  
  
    /** post 
     * @param url     請求的url 
     * @param queries 請求的參數(shù)眯漩,在瀏覽器颗圣?后面的數(shù)據(jù),沒有可以傳null 
     * @param params  post form 提交的參數(shù) 
     * @return 
     * @throws IOException 
     */  
    public static String post(String url, Map<String, String> queries, Map<String, String> params) throws IOException {  
        String responseBody = "";  
        CloseableHttpClient httpClient = getHttpClient();  
        StringBuilder sb = new StringBuilder(url);  
        if (queries != null && queries.keySet().size() > 0) {  
            boolean firstFlag = true;  
            Iterator<Map.Entry<String, String>> iterator = queries.entrySet().iterator();  
            while (iterator.hasNext()) {  
                Map.Entry<String, String> entry = iterator.next();  
                if (firstFlag) {  
                    sb.append("?" + (String) entry.getKey() + "=" + (String) entry.getValue());  
                    firstFlag = false;  
                } else {  
                    sb.append("&" + (String) entry.getKey() + "=" + (String) entry.getValue());  
                }  
            }  
        }  
        //指定url,和http方式  
        HttpPost httpPost = new HttpPost(sb.toString());  
        if (SetTimeOut) {  
            RequestConfig requestConfig = RequestConfig.custom()  
                    .setSocketTimeout(SocketTimeout)  
                    .setConnectTimeout(ConnectTimeout).build();//設(shè)置請求和傳輸超時時間  
            httpPost.setConfig(requestConfig);  
        }  
        //添加參數(shù)  
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();  
        if (params != null && params.keySet().size() > 0) {  
            Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();  
            while (iterator.hasNext()) {  
                Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next();  
                nvps.add(new BasicNameValuePair((String) entry.getKey(), (String) entry.getValue()));  
            }  
        }  
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));  
        //請求數(shù)據(jù)  
        CloseableHttpResponse response = httpClient.execute(httpPost);  
        try {  
            logger.debug("Executing request " + httpPost.getRequestLine());
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {  
                HttpEntity entity = response.getEntity();  
                responseBody = EntityUtils.toString(entity);  
                logger.debug(responseBody);
                EntityUtils.consume(entity);  
            } else {  
                logger.debug("http return status error:" + response.getStatusLine().getStatusCode());
            }  
        } catch (Exception e) {  
            logger.debug("post請求時發(fā)生錯誤~");
        } finally {  
            response.close();  
        }  
        return responseBody;  
    }  
    
    /**
     * 表單提交
     * @param url
     * @param queries
     * @param params
     * @param files
     * @return
     * @throws Exception
     */
    public static String postForm(String url, Map<String, String> queries, Map<String, String> params, Map<String, File> files) throws Exception {
        String responseBody = "";  
        CloseableHttpClient httpClient = getHttpClient();  
        StringBuilder sb = new StringBuilder(url);  
        if (queries != null && queries.keySet().size() > 0) {  
            boolean firstFlag = true;  
            Iterator<Map.Entry<String, String>> iterator = queries.entrySet().iterator();  
            while (iterator.hasNext()) {  
                Map.Entry<String, String> entry = iterator.next();  
                if (firstFlag) {  
                    sb.append("?" + (String) entry.getKey() + "=" + (String) entry.getValue());  
                    firstFlag = false;  
                } else {  
                    sb.append("&" + (String) entry.getKey() + "=" + (String) entry.getValue());  
                }  
            }  
        }  
        //指定url,和http方式  
        HttpPost httpPost = new HttpPost(sb.toString());  
        if (SetTimeOut) {  
            RequestConfig requestConfig = RequestConfig.custom()  
                    .setSocketTimeout(SocketTimeout)  
                    .setConnectTimeout(ConnectTimeout).build();//設(shè)置請求和傳輸超時時間  
            httpPost.setConfig(requestConfig);  
        }  
        MultipartEntityBuilder form = MultipartEntityBuilder.create();
        if (params != null && params.keySet().size() > 0) {  
            Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();  
            while (iterator.hasNext()) {  
                Map.Entry<String, String> entry = iterator.next();  
                StringBody body = new StringBody((String) entry.getValue(), ContentType.create("text/plain", Consts.UTF_8));
                form.addPart((String) entry.getKey(), body);
            }  
        }
        if(files != null && files.keySet().size() > 0){
            Iterator<Map.Entry<String, File>> iterator = files.entrySet().iterator();
            while(iterator.hasNext()){
                Map.Entry<String, File> entry = iterator.next();
                FileBody body9 = new FileBody(entry.getValue());
                form.addPart(entry.getKey(), body9);
            }
        }
        HttpEntity entity = form.build();
        httpPost.setEntity(entity);  
        //請求數(shù)據(jù)  
        CloseableHttpResponse response = httpClient.execute(httpPost);  
        try {  
            logger.debug("Executing request " + httpPost.getRequestLine());
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {  
                HttpEntity responseEntity = response.getEntity();  
                responseBody = EntityUtils.toString(responseEntity);  
                logger.debug(responseBody);
                EntityUtils.consume(responseEntity);  
            } else {  
                logger.debug("http return status error:" + response.getStatusLine().getStatusCode());
            }  
        } catch (Exception e) {  
            logger.debug("post表單時發(fā)生錯誤~");
        } finally {  
            response.close();  
        }  
        return responseBody;  
    }; 
}  
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市统锤,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌炭庙,老刑警劉巖饲窿,帶你破解...
    沈念sama閱讀 212,884評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異焕蹄,居然都是意外死亡逾雄,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,755評論 3 385
  • 文/潘曉璐 我一進店門腻脏,熙熙樓的掌柜王于貴愁眉苦臉地迎上來鸦泳,“玉大人,你說我怎么就攤上這事永品∽鲇ィ” “怎么了?”我有些...
    開封第一講書人閱讀 158,369評論 0 348
  • 文/不壞的土叔 我叫張陵鼎姐,是天一觀的道長钾麸。 經(jīng)常有香客問我更振,道長,這世上最難降的妖魔是什么饭尝? 我笑而不...
    開封第一講書人閱讀 56,799評論 1 285
  • 正文 為了忘掉前任肯腕,我火速辦了婚禮,結(jié)果婚禮上钥平,老公的妹妹穿的比我還像新娘乎芳。我一直安慰自己,他們只是感情好帖池,可當(dāng)我...
    茶點故事閱讀 65,910評論 6 386
  • 文/花漫 我一把揭開白布奈惑。 她就那樣靜靜地躺著,像睡著了一般睡汹。 火紅的嫁衣襯著肌膚如雪肴甸。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 50,096評論 1 291
  • 那天囚巴,我揣著相機與錄音原在,去河邊找鬼。 笑死彤叉,一個胖子當(dāng)著我的面吹牛庶柿,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播秽浇,決...
    沈念sama閱讀 39,159評論 3 411
  • 文/蒼蘭香墨 我猛地睜開眼浮庐,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了柬焕?” 一聲冷哼從身側(cè)響起审残,我...
    開封第一講書人閱讀 37,917評論 0 268
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎斑举,沒想到半個月后搅轿,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,360評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡富玷,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,673評論 2 327
  • 正文 我和宋清朗相戀三年璧坟,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片赎懦。...
    茶點故事閱讀 38,814評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡雀鹃,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出铲敛,到底是詐尸還是另有隱情褐澎,我是刑警寧澤,帶...
    沈念sama閱讀 34,509評論 4 334
  • 正文 年R本政府宣布伐蒋,位于F島的核電站工三,受9級特大地震影響迁酸,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜俭正,卻給世界環(huán)境...
    茶點故事閱讀 40,156評論 3 317
  • 文/蒙蒙 一奸鬓、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧掸读,春花似錦串远、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,882評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至肾请,卻和暖如春留搔,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背铛铁。 一陣腳步聲響...
    開封第一講書人閱讀 32,123評論 1 267
  • 我被黑心中介騙來泰國打工隔显, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人饵逐。 一個月前我還...
    沈念sama閱讀 46,641評論 2 362
  • 正文 我出身青樓括眠,卻偏偏與公主長得像,于是被迫代替她去往敵國和親倍权。 傳聞我的和親對象是個殘疾皇子掷豺,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 43,728評論 2 351

推薦閱讀更多精彩內(nèi)容

  • 轉(zhuǎn)載地址 image.png 前言 fiddler是一個很好的抓包工具,默認是抓http請求的账锹,對于pc上的htt...
    菜菜編程閱讀 21,116評論 0 28
  • OkGo萌业,一個專注于讓網(wǎng)絡(luò)請求更簡單的框架,與RxJava完美結(jié)合奸柬,比Retrofit更簡單易用。 OkGo - ...
    壓抑的內(nèi)心閱讀 16,462評論 0 9
  • Swift1> Swift和OC的區(qū)別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴謹 對...
    cosWriter閱讀 11,093評論 1 32
  • 原因 在現(xiàn)實項目中婴程,由于開發(fā)的經(jīng)常調(diào)試廓奕,接口的不穩(wěn)定,和接口文檔的不及時更新档叔,我們選擇做接口測試桌粉,更多的需要自己抓...
    我為峰2014閱讀 3,086評論 1 5
  • 每個人都說,只要去寫了衙四,就一定會越寫越好的铃肯。最開始的時候我也是這樣想的。不得不說传蹈,以前的想法是對的押逼。 為什么后來變...
    小藍的練習(xí)本閱讀 44評論 0 0