Java 模拟cookie登陆 Java 模拟cookie登陆简单操作示例
程序媛-jjl 人气:0本文实例讲述了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程序设计有所帮助。
加载全部内容