`

用java模拟curl利用cookie登录抓取一个受密码保护的新页面 ( by quqi99 )

 
阅读更多

用java模拟curl利用cookie登录抓取一个受密码保护的新页面 ( by quqi99 )



作者:张华 发表于:2011-01-11

版权声明:可以任意转载,转载时请务必以超链接形式标明文章原始出处和作者信息及本版权声明


本文主要是如何灵活应用HttpURLConnection,代码内容包括:

1)以GET或POST方式获取网页正文及HTTP头信息

2)调用登录接口进行登录,然后获取到登录后的cookie

3)用获取到的cookie去访问一个受密码保护的新页面。

代码如下:



import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import com.TripResearch.util.StringUtils;
import com.TripResearch.util.Utils;

/**
*
*
* @author: huazhang
* @since: 2011-4-15
*/

public class AutoTop
{

public final static String CONTENT_TYPE = "Content-Type";

public static Content curl(String method, String sUrl, Map<String, String> paramMap,
Map<String, String> requestHeaderMap, boolean isOnlyReturnHeader)
{
Content content = null;
HttpURLConnection httpUrlConnection = null;
InputStream in = null;
try
{
URL url = new URL(sUrl);
boolean isPost = "POST".equals(method);
if (Utils.isEmptyString(method) || (!"GET".equalsIgnoreCase(method) && !"POST".equalsIgnoreCase(method)))
{
method = "POST";
}
URL resolvedURL = url;
if ("GET".equals(method) && !Utils.isEmptySafe(paramMap))
{
boolean firstParam = true;
StringBuffer newUrlBuffer = new StringBuffer(url.toExternalForm());
if (url.getQuery() == null)
{
newUrlBuffer.append("?");
}
else
{
newUrlBuffer.append("&");
}
for (Map.Entry<String, String> entry : paramMap.entrySet())
{
String encName = URLEncoder.encode(entry.getKey(), StringUtils.ENC_DESC_UTF8);
if (firstParam)
{
firstParam = false;
}
else
{
newUrlBuffer.append("&");
}
String encValue = URLEncoder.encode(entry.getValue(), StringUtils.ENC_DESC_UTF8);
newUrlBuffer.append(encName);
newUrlBuffer.append("=");
newUrlBuffer.append(encValue);
}
resolvedURL = new java.net.URL(newUrlBuffer.toString());
}

URLConnection urlConnection = resolvedURL.openConnection();
httpUrlConnection = (HttpURLConnection) urlConnection;
httpUrlConnection.setRequestMethod(method);
// Do not follow redirects, We will handle redirects ourself
httpUrlConnection.setInstanceFollowRedirects(false);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
urlConnection.setUseCaches(false);
urlConnection.setDefaultUseCaches(false);
// set request header
if (!Utils.isEmptySafe(requestHeaderMap))
{
for (Map.Entry<String, String> entry : requestHeaderMap.entrySet())
{
String key = entry.getKey();
String val = entry.getValue();
if (key != null && val != null)
{
urlConnection.setRequestProperty(key, val);
}
}
}
if (isPost)
{
urlConnection.setDoOutput(true);
ByteArrayOutputStream bufOut = new ByteArrayOutputStream();
boolean firstParam = true;
for (Map.Entry<String, String> entry : paramMap.entrySet())
{
String encName = URLEncoder.encode(entry.getKey(), StringUtils.ENC_DESC_UTF8);
if (firstParam)
{
firstParam = false;
}
else
{
bufOut.write((byte) '&');
}
String encValue = URLEncoder.encode(entry.getValue(), StringUtils.ENC_DESC_UTF8);
bufOut.write(encName.getBytes(StringUtils.ENC_DESC_UTF8));
bufOut.write((byte) '=');
bufOut.write(encValue.getBytes(StringUtils.ENC_DESC_UTF8));
}
byte[] postContent = bufOut.toByteArray();
if (urlConnection instanceof HttpURLConnection)
{
((HttpURLConnection) urlConnection).setFixedLengthStreamingMode(postContent.length);
}
OutputStream postOut = urlConnection.getOutputStream();
postOut.write(postContent);
postOut.flush();
postOut.close();
}
int responseCode = httpUrlConnection.getResponseCode();
// We handle redirects ourself
if (responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP)
{
String location = httpUrlConnection.getHeaderField("Location");
URL newAction = new URL(url, location);
// Recurse
StringBuffer newUrlSb = new StringBuffer(newAction.getProtocol() + "://" + newAction.getHost());
if (newAction.getPort() != -1)
{
newUrlSb.append(":" + newAction.getPort());
}
if (newAction.getPath() != null)
{
newUrlSb.append(newAction.getPath());
}
if (newAction.getQuery() != null)
{
newUrlSb.append("?" + newAction.getQuery());
}
if (newAction.getRef() != null)
{
newUrlSb.append("#" + newAction.getRef());
}
return curl("GET", newUrlSb.toString(), null, requestHeaderMap, isOnlyReturnHeader);
}
else if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED)
{
byte[] bytes = new byte[0];
if (!isOnlyReturnHeader)
{
in = httpUrlConnection.getInputStream();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
while (true)
{
int rc = in.read(buf);
if (rc <= 0)
{
break;
}
else
{
bout.write(buf, 0, rc);
}
}
bytes = bout.toByteArray();
in.close();
}
// only fetch Content-Length and Last-Modified header
String encoding = null;
if (Utils.isEmptyString(encoding))
{
encoding = getEncodingFromContentType(httpUrlConnection.getHeaderField(CONTENT_TYPE));
}
content = new Content(sUrl, new String(bytes, encoding), httpUrlConnection.getHeaderFields());
}
}
catch (Exception e)
{
Utils.ERR(e);
return null;
}
finally
{
if (httpUrlConnection != null)
{
httpUrlConnection.disconnect();
}
}
return content;
}

public static String getEncodingFromContentType(String contentType)
{
String encoding = null;
if (Utils.isEmptyString(contentType))
{
return null;
}
StringTokenizer tok = new StringTokenizer(contentType, ";");
if (tok.hasMoreTokens())
{
tok.nextToken();
while (tok.hasMoreTokens())
{
String assignment = tok.nextToken().trim();
int eqIdx = assignment.indexOf('=');
if (eqIdx != -1)
{
String varName = assignment.substring(0, eqIdx).trim();
if ("charset".equalsIgnoreCase(varName))
{
String varValue = assignment.substring(eqIdx + 1).trim();
if (varValue.startsWith("/"") && varValue.endsWith("/""))
{
// substring works on indices
varValue = varValue.substring(1, varValue.length() - 1);
}
if (Charset.isSupported(varValue))
{
encoding = varValue;
}
}
}
}
}
if (Utils.isEmptyString(encoding))
{
return StringUtils.ENC_DESC_UTF8;
}
return encoding;
}

public static void main(String[] args)
{
// login
String email = "";
String pass = "";
String loginUrl = "http://www.quqi.com/Login";
String rateReviewUrl = "http://www.quqi.com/RateUserReview";
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("email", email);
paramMap.put("pass", pass);
Content content = curl("POST", loginUrl, paramMap, null, false);

// build request headers & do rate of user review
List<String> cookieList = content.getHeaders().get("Set-Cookie");
Map<String, String> requestHeaders = new HashMap<String, String>();
if (!Utils.isEmptySafe(cookieList))
{
StringBuffer sb = new StringBuffer();
boolean isLast = false;
int i = 0;
for (String val : cookieList)
{
i++;
if(i == cookieList.size())
{
isLast = true;
}
int pos = val.indexOf("=");
if (pos != -1)
{
String cookieName = val.substring(0, pos);
String cookieVal = val.substring(pos + 1);
cookieVal = cookieVal.split(";")[0];
if(isLast)
{
sb.append(cookieName + "=" + cookieVal);
}else
{
sb.append(cookieName + "=" + cookieVal + ";");
}
}
}
requestHeaders.put("Cookie", sb.toString());
}
paramMap = new HashMap<String, String>();
paramMap.put("rateValue", "1");
content = curl("POST", rateReviewUrl, paramMap, requestHeaders, false);

System.out.println(content.getBody());
}

}

class Content
{
private String url;
private String body;
private Map<String, List<String>> m_mHeaders = new HashMap<String, List<String>>();

public Content(String url, String body, Map<String, List<String>> headers)
{
this.url = url;
this.body = body;
this.m_mHeaders = headers;
}

public String getUrl()
{
return url;
}

public String getBody()
{
return body;
}

public Map<String, List<String>> getHeaders()
{
return m_mHeaders;
}

}

分享到:
评论

相关推荐

    PHP使用Curl实现模拟登录及抓取数据功能示例

    本文实例讲述了PHP使用Curl实现模拟登录及抓取数据功能。分享给大家供大家参考,具体如下: 使用PHP的Curl扩展库可以模拟实现登录,并抓取一些需要用户账号登录以后才能查看的数据。具体实现的流程如下(个人总结)...

    php利用curl模拟登录

    curl是一个利用URL语法在命令行方式下工作的文件传输工具。该资源通过具体实例模拟页面登录。curl使用基本过程:第一步:使用curl_init()进行初始化,第二步:使用curl_setopt()函数进行设置选项,第三步:使用curl_...

    ownCloud java使用curl上传文件

    服务器上传文件到ownCloud私有云,java调用curl上传,代码简单

    PHP如何获取Cookie并实现模拟登录

    一、定义Cookie存储路径 必须使用绝对路径 $cookie_jar = dirname(__FILE__).”/pic.cookie”; 二、获取Cookie 将cookie存入文件 $url = "http://1.2.3.4/"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $...

    java--curl工具,用于生成curl链接,直接在服务器上使用

    这个注解主要用在spring -cloud 的feign的class上面,被注解的class下的所有http请求都会生成curl链接

    php通过curl添加cookie伪造登陆抓取数据的方法

    主要介绍了php通过curl添加cookie伪造登陆抓取数据的方法,涉及PHP基于curl操作cookie及页面抓取的相关技巧,需要的朋友可以参考下

    通过CURL命令实现模拟登陆

    使用CURL进行模拟登陆,在一些自动化场景中,相关脚本部署在Linux上,并且是命令行的操作方式,模拟页面的操作基本无法实现,本例使用curl模拟http请求,实现浏览器操作

    使用CURL抓取网页数据

    一个完整的使用CURL抓取网页数据 使用stl string分析网页数据,将提取的数据输出到log.txt中

    PHP cURL模拟浏览器登录

    PHP cURL实现模拟登录与采集使用方法详解教程 PDF

    php应用curl扩展抓取网页类.zip

    介绍一个php应用curl扩展抓取网页类,获取的信息以文件流的形式返回,而不是直接输出。正则方式抓取,抓取标题,抓取文章内容,获取抓取数据,最后进行一下测试。

    curl模拟post类必须精品

    curl模拟post跨域提交数据 包括cookie,agent

    使用PHP curl模拟浏览器抓取网站信息

    官方解释curl是一个利用URL语法在命令行方式下工作的文件传输工具。curl是一个利用URL语法在命令行方式下工作的文件传输工具。它支持很多协议:FTP, FTPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE 以及 LDAP。curl...

    PHP Curl模拟登录微信公众平台、新浪微博实例代码

    下面一段代码给大家介绍php使用curl模拟登录微信公众平台,具体代码如下所示: &lt;?php //模拟微信登入 $cookie_file = tempnam('./temp','cookie'); $login_url = 'https://mp.weixin.qq.com/cgi-bin/login'; $...

    curl配合simple_html_dom进行页面数据抓取

    curl配合simple_html_dom进行页面数据抓取, 扩展是自己写的,在项目中已经实践过很好用,只需要传入简单的参数就可以,省去写大量正则的烦恼,案例是抓取百度搜索

    PHP带cookie执行curl以模拟登录状态的实现代码

    程序里的URL就自己去改了,方法也很简单,程序开始时先执行一个需要登录后才能查看的URL,当然很明显这样执行的结果就是页面会跳转到登录页面的,然后再执行一下登录的程序(当然这里就比较简单的了,如果有网站带了...

    PHP读取CURL模拟登录时生成Cookie文件的方法

    在使用PHP中的CURL模拟登录时会保存一个Cookie文件,例如下面的代码 复制代码 代码如下:$login_url = ‘XXX’;    $post_fields[’email’] = ‘XXXX’;  $post_fields[‘password’] = ‘XXXX’;  $post_fields...

    网页抓取工具curl

    curl.exe

    curl-java-trunk.tar.gz

    curl-java 对于做一些自动登陆中带有js脚本的网页编程不错

    curl模拟登陆源码

    PHPcurl模拟登陆教务系统源码,这里以武汉理工大学教务系统为例,可以自己在此基础上研究其他教务系统。

Global site tag (gtag.js) - Google Analytics