在网站中,很多时候都会遇到需要登陆的情况,记得大一的时候有一些抢课系统,那时候很羡慕这些程序,认为很神奇,只有大佬级的人物才能做出来这些程序,但是后来学了爬虫才发现,这只是一个简单的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);
}
}
}