Java訪問重定向接口

背景:開發作了一個免登錄的接口,方便我後續給管理後臺作一些小工具,問題來了,給的免登錄接口是個302如圖的test_login,在重定向一個200的接口(eload_admin),php

本來開始這樣作:02這個免登錄接口時,獲取登陸的cookies,在把登陸後的cookies給200的接口,就是正常登陸成功cookie

如圖:登陸成功後獲200頁面顯示的內容session就表示獲取了登陸態session

 

問題:但是在代碼中實施遇到一個問題,獲取到的coookie在放到下一個接口不行,弄了很久,以後誤打誤撞發現,在我訪問302的這個接口時,應該先get,在從新get獲取cookie,就是須要作兩次get,代碼以下app

public static void main(String[] args) throws ScriptException {

    System.out.println("重定向接口:"+htppResopnes.get("http://rosegal.com.trunk.s1.egomsl.com/datafeed/test_login.php?tts=a05b3726d9ba6a6947734e4ef0504ffb"));//請求一次url
    String getcookie=htppResopnes.getCookie("http://rosegal.com.trunk.s1.egomsl.com/datafeed/test_login.php?tts=a05b3726d9ba6a6947734e4ef0504ffb");//在請求獲取cookie
    String getseesion=until.getMapValue(getcookie, "RG_SESSIONID");//獲取seesion
    //判斷是否登陸
    System.out.println("登陸成功:"+htppResopnes.get("http://rosegal.com.trunk.s1.egomsl.com/eload_admin/",getseesion));工具

}

 

 htppResopnes的方法url

須要注意的是,由於我在請求兩個接口的時候用到一個getcookie,和一個get,這裏就須要保證他們的頭部cookie是須要一致的,這裏由於當時設置不一致,致使訪問也是失敗的spa

    /**
     * 向指定URL發送GET方法的請求,並攜帶指定cookie
     * @param url 發送請求的URL
     * @param cookies 請求時攜帶的cookie
     * @return Result 所表明遠程資源的響應,頭信息
     * 
     */
    public static Map<String, String> get(String url,String cookies) {
        Cookie staging = null;
        //Cookie ORIGINDC = null;
        int defaultConnectTimeOut = 50000; // 默認鏈接超時,毫秒
        int defaultReadTimeOut = 50000; // 默認讀取超時,毫秒
        
        Map<String, String> result = new HashMap<String, String>();
        BufferedReader in = null;

        try {
            // 打開和URL之間的鏈接
            URLConnection connection = new URL(url).openConnection();
            // 此處的URLConnection對象其實是根據URL的請求協議(此處是http)生成的URLConnection類的子類HttpURLConnection
            // 故此處最好將其轉化爲HttpURLConnection類型的對象,以便用到HttpURLConnection更多的API.
            HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
            //httpURLConnection.setInstanceFollowRedirects(false);
            // 設置通用的請求屬性
            httpURLConnection.setRequestProperty("accept", "*/*");
            httpURLConnection.setRequestProperty("connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
            httpURLConnection.setRequestProperty("Cookie","LPVID=NiNTJlMDdhOWIxMTM0N2Zm; cookieid=10023149924547802009973797079868836; scarab.visitor=%2231990FE0AA92EF1D%22; cookie_lang=en; bizhong=USD; first_access=yes; rosegal_us=visit; rosegal_caen=visit; _ga=GA1.2.2047632407.1495188930; RG_SESSIONID="+cookies);
            httpURLConnection.setConnectTimeout(defaultConnectTimeOut);
            httpURLConnection.setReadTimeout(defaultReadTimeOut);
            // 創建鏈接
            httpURLConnection.connect();
            
            result = getResponse(httpURLConnection, in, result);

        } catch (Exception requestException) {
            System.err.println("發送GET請求出現異常!" + requestException);
        }
        // 關閉輸入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception closeException) {
                closeException.printStackTrace();
            }
        }
        
        return result;
    }



/**
     * 根據返回碼處理返回值
     * @param httpURLConnection
     * @param in
     * @param result
     * @return
     * @throws UnsupportedEncodingException
     * @throws IOException
     */
    public static Map<String, String> getResponse(HttpURLConnection httpURLConnection, BufferedReader in, Map<String, String> result)
            throws UnsupportedEncodingException, IOException {
        int contentLengthAllow = -1; // 返回報文長度限制, 爲-1時不限制長度

        boolean flag = false;
        for (int i = 0; i < successCode.length; i++) {
            if (successCode[i] == httpURLConnection.getResponseCode()) {
                flag = true;
                break;
            }
        }

        // 返回碼非「successCode」時,response爲返回message
        if (flag) {
            // 定義 BufferedReader輸入流來讀取URL的響應
            in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
            String line;

            // 獲取全部響應頭字段
            Map<String, List<String>> Hearder = httpURLConnection.getHeaderFields();
            for (String key : Hearder.keySet()) {
                result.put(key, Hearder.get(key).toString());
            }

            String responseStr = "";
            while ((line = in.readLine()) != null) {
                responseStr += line;
            }

            // Content長度限制
            if (responseStr.length() > contentLengthAllow && contentLengthAllow > 0) {
                responseStr = responseStr.substring(0, contentLengthAllow);
            }

            result.put("Message", httpURLConnection.getResponseMessage());
            result.put("Code", String.valueOf(httpURLConnection.getResponseCode()));
            result.put("Response", responseStr);
        } else {
            result.put("Message", httpURLConnection.getResponseMessage());
            result.put("Code", String.valueOf(httpURLConnection.getResponseCode()));
            //
            result.put("Response", httpURLConnection.getResponseMessage());
            // 獲取全部響應頭字段
            Map<String, List<String>> Hearder = httpURLConnection.getHeaderFields();
            for (String key : Hearder.keySet()) {
                result.put(key, Hearder.get(key).toString());
            }
        }
        return result;
    }
    
/**
     * 獲取請求的cookie
     * @return String
     * @param url:請求的url
     * 建立時間:2017-03-04,最後更新時間:2017-03-04
     */
    public static String getCookie(String url) {

        int defaultConnectTimeOut = 30000; // 默認鏈接超時,毫秒
        int defaultReadTimeOut = 30000; // 默認讀取超時,毫秒
        String CookieStr = "";

        BufferedReader in = null;
        try {
            String cookieskey = "Set-Cookie";
            URLConnection connection = new URL(url).openConnection();
            HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
            httpURLConnection.setInstanceFollowRedirects(false); 這個就是開啓重定向
            
            httpURLConnection.setRequestProperty("accept", "*/*");
            httpURLConnection.setRequestProperty("connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
            httpURLConnection.setRequestProperty("Cookie", "LPVID=NiNTJlMDdhOWIxMTM0N2Zm; cookieid=10023149924547802009973797079868836; scarab.visitor=%2231990FE0AA92EF1D%22; cookie_lang=en; bizhong=USD; first_access=yes; rosegal_us=visit; rosegal_caen=visit; _ga=GA1.2.2047632407.1495188930");
            httpURLConnection.setConnectTimeout(defaultConnectTimeOut);
            httpURLConnection.setReadTimeout(defaultReadTimeOut);
        /*    if (staging != null) {
                httpURLConnection.setRequestProperty("Cookie", staging.toString());
            }
            if (ORIGINDC != null) {
                httpURLConnection.setRequestProperty("Cookie", ORIGINDC.toString());
                ORIGINDC = null;
            }*/

            // 創建鏈接
            httpURLConnection.connect();

            // 從請求中獲取cookie列表
            
            
            Map<String, List<String>> maps = httpURLConnection.getHeaderFields();
            List<String> coolist = maps.get(cookieskey);
            Iterator<String> it = coolist.iterator();
            StringBuffer sbu = new StringBuffer();
            // 拼接cookie再請求
            sbu.append("eos_style_cookie=default; ");
            while (it.hasNext()) {
                sbu.append(it.next() + ";");
            }
            CookieStr = sbu.toString();
            CookieStr = CookieStr.substring(0, CookieStr.length() - 1);
            System.out.println("**************CookieStr:" + CookieStr);
        } catch (Exception requestException) {
            System.err.println("發送GET請求出現異常!" + requestException);
        }
        // 關閉輸入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception closeException) {
                closeException.printStackTrace();
            }
        }
        return CookieStr;
    }
相關文章
相關標籤/搜索