Java 模擬cookie登陸簡單操作示例
本文實例講述了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); }}
更多關(guān)于java算法相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點技巧總結(jié)》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設(shè)計有所幫助。
相關(guān)文章:
1. Android 實現(xiàn)徹底退出自己APP 并殺掉所有相關(guān)的進(jìn)程2. Vue實現(xiàn)仿iPhone懸浮球的示例代碼3. vue使用moment如何將時間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時間格式4. 一個 2 年 Android 開發(fā)者的 18 條忠告5. js select支持手動輸入功能實現(xiàn)代碼6. Spring的異常重試框架Spring Retry簡單配置操作7. Android studio 解決logcat無過濾工具欄的操作8. 什么是Python變量作用域9. PHP正則表達(dá)式函數(shù)preg_replace用法實例分析10. vue-drag-chart 拖動/縮放圖表組件的實例代碼
