博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
HttpURLConnection模拟登录方法(带Cookie的POST/GET)
阅读量:2386 次
发布时间:2019-05-10

本文共 4323 字,大约阅读时间需要 14 分钟。

https://blog.csdn.net/kimqcn4/article/details/52473085

[java]   
  1. // http://blog.csdn.net/woxueliuyun/article/details/43267365  
  2. package tool  
  3.    
  4. class MyHttpUrlConn {  
  5.     public static String cookieVal=""  
  6.   
  7.     public static void Get(String url_get,String str_param_url,String charset,String cookie) throws IOException  {  
  8.         // 拼凑get请求的URL字串,使用URLEncoder.encode对特殊和不可见字符进行编码  
  9.         //    String getURL = GET_URL + "?username="  + URLEncoder.encode("fat man", "utf-8");  
  10.         String getURL = url_get + "?" + str_param_url  
  11.         URL getUrl = new URL(getURL);  
  12.         // 根据拼凑的URL,打开连接,URL.openConnection函数会根据URL的类型,  
  13.         // 返回不同的URLConnection子类的对象,这里URL是一个http,因此实际返回的是HttpURLConnection  
  14.         HttpURLConnection connection = (HttpURLConnection) getUrl  
  15.                 .openConnection();  
  16.   
  17.         if (cookie != null) {  
  18.             //发送cookie信息上去,以表明自己的身份,否则会被认为没有权限  
  19.             println("set cookieVal = [" + cookie + "]")  
  20.             connection.setRequestProperty("Cookie", cookie);  
  21.         }  
  22.   
  23.         // 进行连接,但是实际上get request要在下一句的connection.getInputStream()函数中才会真正发到  
  24.         // 服务器  
  25.         connection.connect();  
  26.         // 取得输入流,并使用Reader读取  
  27.         BufferedReader reader = new BufferedReader(new InputStreamReader(  
  28.                 connection.getInputStream(),charset));  
  29.         System.out.println("Contents of get request:");  
  30.         String lines;  
  31.         while ((lines = reader.readLine()) != null)  {  
  32.              System.out.println(lines);  
  33.         }  
  34.         println(" ")  
  35.         reader.close();  
  36.         // 断开连接  
  37.         connection.disconnect();  
  38.     }  
  39.   
  40.     public static String Post(String url_post,String str_param_body,String charset,boolean b_flag,String cookies) throws IOException  {  
  41.         // Post请求的url,与get不同的是不需要带参数  
  42.         URL postUrl = new URL(url_post);  
  43.         // 打开连接  
  44.         HttpURLConnection connection = (HttpURLConnection) postUrl  
  45.                 .openConnection();  
  46.         // Output to the connection. Default is  
  47.         // false, set to true because post  
  48.         // method must write something to the  
  49.         // connection  
  50.         // 设置是否向connection输出,因为这个是post请求,参数要放在  
  51.         // http正文内,因此需要设为true  
  52.         if("" != cookies){  
  53.             connection.setRequestProperty("Cookie", cookies);  
  54.         }  
  55.   
  56.         connection.setDoOutput(true);  
  57.         // Read from the connection. Default is true.  
  58.         connection.setDoInput(true);  
  59.         // Set the post method. Default is GET  
  60.         connection.setRequestMethod("POST");  
  61.         // Post cannot use caches  
  62.         // Post 请求不能使用缓存  
  63.         connection.setUseCaches(false);  
  64.         // This method takes effects to  
  65.         // every instances of this class.  
  66.         // URLConnection.setFollowRedirects是static函数,作用于所有的URLConnection对象。  
  67.         // connection.setFollowRedirects(true);  
  68.   
  69.         // This methods only  
  70.         // takes effacts to this  
  71.         // instance.  
  72.         // URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数  
  73.         connection.setInstanceFollowRedirects(b_flag);  
  74.         // Set the content type to urlencoded,  
  75.         // because we will write  
  76.         // some URL-encoded content to the  
  77.         // connection. Settings above must be set before connect!  
  78.         // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的  
  79.         // 意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode  
  80.         // 进行编码  
  81.         connection.setRequestProperty("Content-Type",  
  82.                 "application/x-www-form-urlencoded");  
  83.         // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,  
  84.         // 要注意的是connection.getOutputStream会隐含的进行connect。  
  85.         connection.connect();  
  86.         DataOutputStream out = new DataOutputStream(connection  
  87.                 .getOutputStream());  
  88.         // The URL-encoded contend  
  89.         // 正文,正文内容其实跟get的URL中'?'后的参数字符串一致  
  90.         //    String content = "userName=" + URLEncoder.encode("console", "utf-8");  
  91.         //    content = content + "&password=" + URLEncoder.encode("12345678", "utf-8");  
  92.   
  93.         println("http param body = [" + str_param_body + "]")  
  94.         // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面  
  95.         out.writeBytes(str_param_body);  
  96.   
  97.         out.flush();  
  98.   
  99.         // 取得cookie,相当于记录了身份,供下次访问时使用  
  100.         //    cookieVal = connection.getHeaderField("Set-Cookie").split(";")[0]  
  101.         cookieVal = connection.getHeaderField("Set-Cookie")  
  102.         println("get cookieVal = [" + cookieVal  + "]")  
  103.   
  104.         out.close(); // flush and close  
  105.         BufferedReader reader = new BufferedReader(new InputStreamReader(  
  106.                 connection.getInputStream(),charset));  
  107.         String line;  
  108.         System.out.println("Contents of post request:");  
  109.         while ((line = reader.readLine()) != null)  {  
  110.             System.out.println(line);  
  111.         }  
  112.         println(" ")  
  113.   
  114.         reader.close();  
  115.         connection.disconnect();  
  116.   
  117.         return cookieVal  
  118.     }  
  119. }  

用法:

String cookie_login = MyHttpUrlConn.Post(URL_LOGIN,"userName=admin&password=12345678","utf-8",false,"");
MyHttpUrlConn.Post(URL_POST_SAVE,"name=mxb&yearsold=6","utf-8",false,cookie_login);MyHttpUrlConn.Get(URL_GET_VIEW,"name=mxb&yearsold=6","utf-8",cookie_login);

说明:

向URL_POST_SAVE Post数据时,要带上URL_LOGIN时生成的cookie,否则无法save数据。

同理Get也是。

你可能感兴趣的文章
数据同步
查看>>
软件安全开发生命周期读书笔记
查看>>
openldap安装笔记
查看>>
GIT中文教程
查看>>
cobit成功案例
查看>>
Linux下的内网反弹实例
查看>>
Apache 漏洞之后缀名解析漏洞
查看>>
Sun Java Web Server version 7.0 update 7 remote stack overflow exploit
查看>>
Command execution with a MySQL UDF
查看>>
more with rpcclient
查看>>
ITIL项目手记四:证券公司ITIL项目的心得
查看>>
WINDOWS下搭建LDAP服务器
查看>>
二进制数据 + MySQL + PHP 怎样在Mysql中直接储存图片
查看>>
For Linux Mysql Udf
查看>>
Perl BackConnectShell + Rootlab t00l
查看>>
JBoss Autopwn Script
查看>>
OTPs: Using s/Key with SSH via OPIE
查看>>
使用arpwatch和arping来排查ARP攻击
查看>>
Linux硬件监控方法
查看>>
Linux系统安全工具之:Sxid和Skey
查看>>