1. 程式人生 > 實用技巧 >httpClient4.5.12,整合Cookie

httpClient4.5.12,整合Cookie

package com.httpclient;

import com.util.CommonMethord;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;


public class TestCookie7 {
    public static void main(String[] args) throws IOException {
        loginPost( "http://192.168.31.193:8080/consumer/loginAction.do?method=login",
                "logonname=admin&password=abc123&logindate=2020-07-31&Submit=");

        doPost( "http://192.168.31.193:8080/consumer/repFileAction.do?method=exportTemplate",
                "urlpkid=&urlreasons=&organ_name=濱海農商行(全轄彙總)&databatch=2020-07-28&organ_id=10&report_id=0&target_id=0");

        doPost( "http://192.168.31.193:8080/consumer/dataFill.do?method=commitDataStatus",
                "organId=10&reportId=1055&dataDate=2020-07-31&targettable=RESULT_COMPLAINT&aaaa=0");


    }

    static String JSESSIONID ;

    public static void doPost(String url, String parameters) throws IOException {
        CloseableHttpClient closeableHttpClient = null;
        try {
            CookieStore cookieStore = new BasicCookieStore();
            BasicClientCookie cookie = new BasicClientCookie( "JSESSIONID", JSESSIONID);
            cookie.setVersion( 0 );
            cookie.setDomain( "192.168.31.193" );
            cookie.setPath( "/consumer" );

            cookieStore.addCookie( cookie );
            closeableHttpClient = HttpClients.custom()
                    .setDefaultCookieStore( cookieStore )
                    .build();
            HttpPost httpPost = new HttpPost( url );
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            // 2 判斷引數不為空值時,進行切割
            if (!CommonMethord.isEmpty( parameters )) {
                String[] parameter_array = parameters.split( "&" );
                for (String line : parameter_array) {
                    String[] parameter = line.split( "=" );
                    if (parameter.length >= 2) {
                        formparams.add( new BasicNameValuePair( parameter[0], parameter[1] ) );
                    } else {
                        formparams.add( new BasicNameValuePair( parameter[0], "" ) );
                    }
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity( formparams, Consts.UTF_8 ); //對引數進行編碼
                httpPost.setEntity( entity );
            }

            System.out.println( httpPost.getRequestLine());
            CloseableHttpResponse httpResponse =null;
            try {
                httpResponse = closeableHttpClient.execute( httpPost );
                HttpEntity entity = httpResponse.getEntity();
                System.out.println(httpResponse.getStatusLine());
                if(entity!=null){
                    System.out.println(EntityUtils.toString( entity,"utf-8" ));
                }
            }catch (IOException e){
                e.printStackTrace();
            }finally {
                httpResponse.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            closeableHttpClient.close();
        }
    }

    // 登入
    public static String loginPost(String url, String parameters) {
        // 1 建立請求連線
        //CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionTimeToLive(6000, TimeUnit.MILLISECONDS)
                .build();

        HttpPost httpPost = new HttpPost( url.trim() );
        httpPost.setHeader(new BasicHeader("Content-type", "application/x-www-form-urlencoded"));



        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        // 2 判斷引數不為空值時,進行切割
        if (!CommonMethord.isEmpty( parameters )) {
            String[] parameter_array = parameters.split( "&" );
            for (String line : parameter_array) {
                String[] parameter = line.split( "=" );
                if (parameter.length >= 2) {
                    formparams.add( new BasicNameValuePair( parameter[0], parameter[1] ) );
                } else {
                    formparams.add( new BasicNameValuePair( parameter[0], "" ) );
                }
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity( formparams, Consts.UTF_8 ); //對引數進行編碼
            httpPost.setEntity( entity );
        }

        // 獲取返回物件
        String result = ""; //
        CloseableHttpResponse resp; //返回結果

        try {
            // 傳送請求
            HttpClientContext localContext = HttpClientContext.create();
            resp = httpClient.execute( httpPost,localContext );

            // Cookie
            List<Cookie> cookies = localContext.getCookieStore().getCookies();

            for(int i= 0; i<cookies.size();i++){
                if (cookies.get( i ).getName().equals( "JSESSIONID" )){
                    JSESSIONID = cookies.get( i ).getValue();
                }
                System.out.println( "========完整值===========" + cookies.get( i ));
                System.out.println( "========完整值===========" + cookies.get( i ).getValue());
            }



            // http 狀態 200 404 302 500
            StatusLine line = resp.getStatusLine(); //返回帶有Cookie
            System.out.println( "狀態返回碼:" + line );

            // 結果
            HttpEntity httpEntity = resp.getEntity();
            if (httpEntity != null) {
                // 結果轉換
                result = EntityUtils.toString( httpEntity, "utf-8" );
//                System.out.println("resp"+ resp.getEntity());
//                System.out.println( result );
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }
}