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 ...
随机推荐
- C# 事务提交(非数据库)
.Net 2.0开始支持 static void Main(string[] args) { using (TransactionScope ts = new TransactionScope()) ...
- Java字符容量capacity()方法
Java字符容量计算:比如StringBuffer sb=new StringBuffer("Good");输出 .
- java——单例模式
这个教程写的真好:https://blog.csdn.net/mnb65482/article/details/80458571 1. 什么是单例模式? 单例模式确保某个类只有一个实例. 单例类必须自 ...
- C# 反射(Reflection)
反射主要用于在程序运行期间动态解析相关类的类名,命名空间,属性,方法并进行相应操作,以下通过两个简单的例子进行了说明: 示例1:调用程序集内部方法,运行时动态获取相关类的信息,包括类名,命名空间等信息 ...
- B-树 B+树 红黑树
B树是一种多路平衡查找树,它的每一个节点最多包含k个孩子,k被称为B树的阶.k的大小取决于磁盘页的大小.B树主要应用于文件系统以及部分数据库索引,比如著名的非关系型数据库MongoDB.一个m阶的B树 ...
- Django-3 视图层
5.1 视图函数 一个视图函数,简称视图,是一个简单的Python 函数,它接受Web请求并且返回Web响应.响应可以是一张网页的HTML内容,一个重定向,一个404错误,一个XML文档,或者一张图片 ...
- DataFrame的数据类型转换
dfxxx['username']=pd.to_numeric(dfxxx['username'],errors='coerce')#将不能转换数据类型的值强制转换成NaN dfxxx['userna ...
- Unity Resources.Load
GameObject bulletPrefab; void Start() { bulletPrefab = Resources.Load("bulletPrefab") a ...
- /proc/sys/net/ipv4/下各参数含义
net.ipv4.tcp_tw_reuse = 0 表示开启重用.允许将TIME-WAIT sockets重新用于新的TCP连接,默认为0,表示关闭 net.ipv4.tcp_tw_recycle = ...
- Quartz使用(3) - Quartz核心接口Trigger
Trigger最常用的有两种SimpleTrigger和CronTrigger,首先介绍Trigger的一些基础的信息,然后会详细描述这两种Trigger. 1. 通用Trigger属性 quartz ...