java网络爬虫3---使用post来实现登陆功能

在网站中,很多时候都会遇到需要登陆的情况,记得大一的时候有一些抢课系统,那时候很羡慕这些程序,认为很神奇,只有大佬级的人物才能做出来这些程序,但是后来学了爬虫才发现,这只是一个简单的post数据的过程,在此分享一个登陆我们学校的教务系统的程序

在登陆时要先找到数据post的地址,一般都不是登陆页面的地址,我比较喜欢用fiddler来查看一下数据post的地址,以及post的表单,下面是一个登陆山东大学的教务系统的程序,要注意密码使用了md5加密方式

详细代码如下:

package java爬虫;
/*HttpClient发送post的例子*/
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class USEHttpClient {

	public static void main(String[] args) throws ClientProtocolException, IOException, Throwable {
		// TODO Auto-generated method stub
		
		//先创建一个客户端,类似于打开一个浏览器
		CloseableHttpClient httpclient=HttpClientBuilder.create().build();
		//创建一个post方法
        HttpPost httppost=new HttpPost("http://bkjwxk.sdu.edu.cn/b/ajaxLogin");
        //输入post的数据
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
        nameValuePairs.add(new BasicNameValuePair("Parameter", "Value"));
        nameValuePairs.add(new BasicNameValuePair("j_username", "你的账号"));
        nameValuePairs.add(new BasicNameValuePair("j_password", "你的密码"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, Charset  
                .forName("gb2312")));
        //类似于在浏览器地址栏中输入回车,获得网页内容
        HttpResponse response=httpclient.execute(httppost);
        //查看返回内容,类似于在浏览器中查看网页源代码
        HttpEntity entity=response.getEntity();
        if(entity!=null) {
        	String html=EntityUtils.toString(entity,"GBK");
        	EntityUtils.consume(entity);//关闭内容流
        	System.out.println(html);
        }
    
	}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值