1. 程式人生 > >httpClient模擬瀏覽器自帶cookie傳送訪問請求

httpClient模擬瀏覽器自帶cookie傳送訪問請求

第一種方式:在get請求中手工增加一個cookie欄位

//建立httpClient
httpClientBuilder=HttpClientBuilder.create();
CloseableHttpClient httpClient=httpClientBuilder.build();

String url="http://192.168.1.222:8080/user/login.do";

        HttpPost httpPost = new HttpPost(url);  
        

        //提交表單資料
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();  
        nvps.add(new BasicNameValuePair("userName", "java1234"));  
        nvps.add(new BasicNameValuePair("password", "123")); 
        nvps.add(new BasicNameValuePair("roleName", "系統管理員"));  
        httpPost.setEntity(new UrlEncodedFormEntity(nvps,"UTF-8"));  
       

        //返回響應
        HttpResponse result=httpClient.execute(httpPost);

        //301或302  重定向 
        if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {  
           
        // 從響應的頭部中取出轉向的地址  
            Header locationHeader = result.getLastHeader("location");  
            String location = null;  
            if (locationHeader != null) {  
                location = locationHeader.getValue();  
                System.out.println(location);


                //獲取重定向的地址,並新建get
                HttpGet httpget = new HttpGet("http://192.168.1.222:8080"+location);
                
                //獲取響應文字中的"Set-Cookie"值
        String cookie=result.getFirstHeader("Set-Cookie").getValue();
        //在httpget請求中 增加cookie欄位,攜帶cookie傳送訪問請求
                httpget.addHeader(new BasicHeader("Cookie",cookie));
                
                
                
                HttpResponse response=httpClient.execute(httpget);

        }

第二種方式:在httpclient裡配置cookie的管理方式,自動管理cookie

//建立自動管理cookie的httpClient
//RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
//CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();