背景:开发做了一个免登陆的接口,方便我后续给管理后台做一些小工具,问题来了,给的免登陆接口是个302如图的test_login,在重定向一个200的接口(eload_admin),
原本开始这样做:02这个免登陆接口时,获取登录的cookies,在把登录后的cookies给200的接口,就是正常登录成功
如图:登录成功后获200页面显示的内容session就表示获取了登录态
问题:但是在代码中实施遇到一个问题,获取到的coookie在放到下一个接口不行,弄了好久,之后误打误撞发现,在我访问302的这个接口时,应该先get,在重新get获取cookie,就是需要做两次get,代码如下
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的方法:
需要注意的是,因为我在请求两个接口的时候用到一个getcookie,和一个get,这里就需要保证他们的头部cookie是需要一致的,这里因为当时设置不一致,导致访问也是失败的
/** * 向指定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; }