本文实例讲述了Java 模拟cookie登陆简单操作。分享给大家供大家参考,具体如下:
最近在做将禅道上的功能接口做到手机端,在做登陆的时候,看了禅道的源码,是由cookie来登陆,所以要做一个模拟cookie登陆的接口,将拿到的cookie放到每次接口请求的头部中去,就可以正常访问了。
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* @Author: jljiang
* @Description:Java 模拟cookie登陆
* @Date: Created in 2019/1/16 15:14
*/
public class ImitateLoginController {
public static void main(String args[]) throws Exception {
//登陆接口地址
String loginStr = "http://zenta.51fb.com/index.php?m=user&f=login";
/**
* 首先要和URL下的URLConnection对话。 URLConnection可以很容易的从URL得到。比如: // Using
* java.net.URL and //java.net.URLConnection
*/
URL url = new URL(loginStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection
.getOutputStream(), "GBK");
//其中的account和password可以通过控制台去查看,或者看页面html去查看
out.write("account=you-user-name&password=you-password");
// remember to clean up
out.flush();
out.close();
// 取得cookie,使用该cookie放在头部就可以访问其他需要登陆才可以访问的接口了
String cookieVal = connection.getHeaderField("Set-Cookie");
/*------------------------------------访问其他接口-------------------------------------------------*/
String otherUrl = "http://zenta.51fb.com/index.php?m=bug&f=browse";
url = new URL(otherUrl);
HttpURLConnection otherConnection = (HttpURLConnection) url.openConnection();
if(cookieVal != null){
otherConnection.setRequestProperty("Cookie",cookieVal);
}
otherConnection.connect();
InputStream urlStream = otherConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(urlStream));
String content = null;
StringBuilder total = new StringBuilder();
while ((content = bufferedReader.readLine()) != null) {
total.append(content);
}
bufferedReader.close();
System.out.println(content);
}
}
更多关于java算法相关内容感兴趣的读者可查看本站专题:《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。