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

    主要是对openpyxl扩展进行扩展,使用归类等 1. 安装 pip install openpyxl 想要在文件中插入图片文件,需要安装pillow,安装文件:PIL-fork-1.1.7.win- ...

  2. TCP/IP协议中几个缩写词的含义 MSL、TTL和RTT 报文最大生存时间 跳数(即生存时间) cs往返时间 MSL要大于TTL知道为什么吗?

    MSL.TTL和RTT简介 1.MSL是Maximum Segment Lifetime英文的缩写,中文可以译为“报文最大生存时间”,他是任何报文在网络上存在的最长时间,超过这个时间报文将被丢弃.因为 ...

  3. SQL---MySQL数据库---聚合函数

    1.数值 format(x,n) 将x格式化为  由逗号分隔,小数点后n 位的数:

  4. 使用cucumber & selenium实现一个简单的bddtest

    1.Cucumber介绍 + feature : read requirement +scenario : testing situation,including + Given/ + when/ + ...

  5. (转)DNS原理及其解析过程

    DNS原理及其解析过程原文:http://blog.51cto.com/369369/812889 网络通讯大部分是基于TCP/IP的,而TCP/IP是基于IP地址的,所以计算机在网络上进行通讯时只能 ...

  6. 读<<programming ruby>> 7.6节 flip-flop 理解

    书中源码是这样的 File.foreach('1.txt') do |x| if(($. == 1) || x =~ /eig/) .. (($. == 3) || x =~ /nin/) then ...

  7. 新浪微博OAuth2授权错误 error:redirect_uri_mismatch

    最近想在app进行新浪微博认证,结果发现总是报error:redirect_uri_mismatch错误. 网上搜了解决方法. 进入 http://open.weibo.com/apps/app_ke ...

  8. Python常用模块二

    一.time & datetime #_*_coding:utf-8_*_ import time # print(time.clock()) #返回处理器时间,3.3开始已废弃 , 改成了t ...

  9. intellijidea课程 intellijidea神器使用技巧2-2 精准搜索

    高效定位: 1 类: 类的跳转: Ctrl shift n ==> 查询类名 Ctrl shift n n ==> jar包中的类 2 文件: Ctrl shift shift n ==& ...

  10. vim基本操作思维导图