Java访问重定向接口
背景:开发做了一个免登陆的接口,方便我后续给管理后台做一些小工具,问题来了,给的免登陆接口是个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访问重定向接口的更多相关文章
- java访问微信接口发送消息
最近在开发activiti流程的时候有个需求:流程到达每个审批节点后,需要向该节点的审批人发送一个消息,提示有审批需要处理. 参考了一下微信的开发者文档和网络上的一些技术博客,现在记录一下.以便后续继 ...
- Spring boot 配置https 实现java通过https接口访问
近来公司需要搭建一个https的服务器来调试接口(服务器用的spring boot框架),刚开始接触就是一顿百度,最后发现互联网认可的https安全链接的证书需要去CA认证机构申请,由于是调试阶段就采 ...
- 在Ubuntu为Android硬件抽象层(HAL)模块编写JNI方法提供Java访问硬件服务接口(老罗学习笔记4)
在上两篇文章中,我们介绍了如何为Android系统的硬件编写驱动程序,包括如何在Linux内核空间实现内核驱动程序和在用户空间实现硬件抽象层接口.实现这两者的目的是为了向更上一层提供硬件访问接口,即为 ...
- JNI的替代者—使用JNA访问Java外部功能接口
摘自:http://www.cnblogs.com/lanxuezaipiao/p/3635556.html JNI的替代者-使用JNA访问Java外部功能接口 1. JNA简单介绍 先说JNI(Ja ...
- 为Android硬件抽象层(HAL)模块编写JNI方法提供Java访问硬件服务接口
在上两篇文章中,我们介绍了如何为Android系统的硬件编写驱动程序,包括如何在Linux内核空间实现内核驱动程序和在用户空间实现硬件抽象层接 口.实现这两者的目的是为了向更上一层提供硬件访问接口,即 ...
- JNI的又一替代者—使用JNR访问Java外部函数接口(jnr-ffi)
1. JNR简单介绍 继上文“JNI的替代者—使用JNA访问Java外部函数接口”,我们知道JNI越来越不受欢迎,JNI是编写Java本地方法以及将Java虚拟机嵌入本地应用程序的标准编程接口.它管理 ...
- “全栈2019”Java第八十一章:外部类能否访问嵌套接口里的成员?
难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java第 ...
- 【C/C++开发】【Java开发】JNI的替代者—使用JNA访问Java外部功能接口
JNI的替代者-使用JNA访问Java外部功能接口 1. JNA简单介绍 先说JNI(Java Native Interface)吧,有过不同语言间通信经历的一般都知道,它允许Java代码和其他语言( ...
- Java调用webservice接口方法
java调用webservice接口 webservice的 发布一般都是使用WSDL(web service descriptive langu ...
随机推荐
- 签名:实现参数字典排序,然后拼接为url参数形式
在很多地方请求参数需要做处理例如: 步骤 1.参数字典排序. 2.拼接字符. /// <summary> /// 生成签名 /// </summary> /// <par ...
- Socket通信客户端和服务端代码
这两天研究了下Socket通信,简单实现的客户端和服务端代码 先上winfrom图片,客户端和服务端一样 服务端代码: using System; using System.Collections.G ...
- java——时间复杂度、动态数组
O(n)不一定小于O(n^2),要具体来看,而我们说的这种时间复杂度其实是渐进时间复杂度,描述的是n趋近于无穷的情况. 动态数组的时间复杂度: 添加操作:O(n) addLast()的均摊复杂度为O( ...
- 在vue2.x中安装sass并配置
在vue中安装sass先检查系统中有没有安装sass,在命令行中输入 sass -v 表示sass在电脑中已有,否者可以参考我这篇博客安装Sass遇到的坑 一.先安装sass cmd打开命令行,到项目 ...
- bzoj1008: [HNOI2008]越狱 数学公式+快速幂
bzoj1008: [HNOI2008]越狱 O(log N)---------------------------------------------------------------- ...
- 查看Python支持的.whl文件版本
AMD64 import pip._internal print(pip._internal.pep425tags.get_supported()) WIN32 import pip print(pi ...
- android Activity启动过程(二)从ActivityManagerService的startActivity到栈顶Activity的onPause过程
ActivityManagerService.startActivity() ActvityiManagerService.startActivityAsUser() ActivityStackSup ...
- Android平台网络常用命令
工作中经常用到的一些命令,整理一下,方便以后进行参考 1.IP设置 ifconfig eth0 128.224.156.81 up //一般的嵌入式linux中设置IP.ifconfig eth0 ...
- Sublime Text格式化HTML JS CSS代码
Sublime Text是开发Hybrid应用的神器,但是有时候对糟糕的代码格式很懊恼,尤其是团队成员比较多,并且代码风格不是很统一的时候.幸好有可用的格式化插件,比较好用的就是HTML-CSS-JS ...
- DEDE文章列表加上序号效果
在文章列表上面加上序号列表的形式,使得文章列表表现得没那么单调,更加丰富一点. {dede:arclist orderby=pubdate type='commend.' titlelen='26' ...