背景:开发做了一个免登陆的接口,方便我后续给管理后台做一些小工具,问题来了,给的免登陆接口是个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;
}

Java访问重定向接口的更多相关文章

  1. java访问微信接口发送消息

    最近在开发activiti流程的时候有个需求:流程到达每个审批节点后,需要向该节点的审批人发送一个消息,提示有审批需要处理. 参考了一下微信的开发者文档和网络上的一些技术博客,现在记录一下.以便后续继 ...

  2. Spring boot 配置https 实现java通过https接口访问

    近来公司需要搭建一个https的服务器来调试接口(服务器用的spring boot框架),刚开始接触就是一顿百度,最后发现互联网认可的https安全链接的证书需要去CA认证机构申请,由于是调试阶段就采 ...

  3. 在Ubuntu为Android硬件抽象层(HAL)模块编写JNI方法提供Java访问硬件服务接口(老罗学习笔记4)

    在上两篇文章中,我们介绍了如何为Android系统的硬件编写驱动程序,包括如何在Linux内核空间实现内核驱动程序和在用户空间实现硬件抽象层接口.实现这两者的目的是为了向更上一层提供硬件访问接口,即为 ...

  4. JNI的替代者—使用JNA访问Java外部功能接口

    摘自:http://www.cnblogs.com/lanxuezaipiao/p/3635556.html JNI的替代者-使用JNA访问Java外部功能接口 1. JNA简单介绍 先说JNI(Ja ...

  5. 为Android硬件抽象层(HAL)模块编写JNI方法提供Java访问硬件服务接口

    在上两篇文章中,我们介绍了如何为Android系统的硬件编写驱动程序,包括如何在Linux内核空间实现内核驱动程序和在用户空间实现硬件抽象层接 口.实现这两者的目的是为了向更上一层提供硬件访问接口,即 ...

  6. JNI的又一替代者—使用JNR访问Java外部函数接口(jnr-ffi)

    1. JNR简单介绍 继上文“JNI的替代者—使用JNA访问Java外部函数接口”,我们知道JNI越来越不受欢迎,JNI是编写Java本地方法以及将Java虚拟机嵌入本地应用程序的标准编程接口.它管理 ...

  7. “全栈2019”Java第八十一章:外部类能否访问嵌套接口里的成员?

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java第 ...

  8. 【C/C++开发】【Java开发】JNI的替代者—使用JNA访问Java外部功能接口

    JNI的替代者-使用JNA访问Java外部功能接口 1. JNA简单介绍 先说JNI(Java Native Interface)吧,有过不同语言间通信经历的一般都知道,它允许Java代码和其他语言( ...

  9. Java调用webservice接口方法

                             java调用webservice接口   webservice的 发布一般都是使用WSDL(web service descriptive langu ...

随机推荐

  1. Python 初识爬虫-**机场出港业务

    # -*- coding:utf-8 -*- from lxml import etree import requests ##先进单页测试,然后在进行多页循环 没有解决的问题,动态解决最大页数,目前 ...

  2. python_文件 处理

    一.字符编码 内存固定使用unicode编码 数据最先产生于内存中,是unicode格式,要想传输需要转成bytes格式 # unicode -------> enconde( u t f - ...

  3. Mybatis学习笔记11 - 动态sql之trim标签

    trim标签体中是整个字符串拼串后的结果.prefix="" 前缀: prefix给拼串后的整个字符串加一个前缀prefixOverrides="" 前缀覆盖: ...

  4. java 与 数据库的连接

    Eclipse中使用SQL server 2017数据库 一.准备材料 要能够使用数据库就要有相应的JDBC,所以我们要去Microsoft官网下载https://www.microsoft.com/ ...

  5. EOF是什么

    我学习C语言的时候,遇到的一个问题就是EOF. 它是end of file的缩写,表示"文字流"(stream)的结尾.这里的"文字流",可以是文件(file) ...

  6. 标准I/O库(详解)(Standard I/O Library)

    文章转自:https://www.cnblogs.com/kingcat/archive/2012/05/09/2491847.html 自己在学习中,对此原文的基础之上进行补充. 什么是缓冲区 缓冲 ...

  7. 用Windows Live Writer离线写博客

    作为CSDN博客的菜鸟,我发现在线写博客很不方便,而且文字编辑也不方便,比如不能傻瓜化地修改字体和颜色."有志者自有千方百计,无志者只感千难万难."一番搜索后,我发现了Window ...

  8. 关于微信小程序登录授权

    小程序的API接口文档写的很清晰,现在理一遍思路. 前端通过wx.login()获取code ,把code发给后台,后台返回openid,再获取用户的授权信息(这里先判断是否授权,授权过的就直接进入小 ...

  9. Node.js资料

    http://developer.51cto.com/art/201109/290443.htmhttp://www.nodebeginner.org/index-zh-cn.html node 各种 ...

  10. 【转】带你正确的使用List的retainAll方法求交集

    一. retainAll 方法 public boolean retainAll(Collection<?> c) { //调用自己的私有方法 return batchRemove(c, ...