package com.ncs.blog.test;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class TestPost {
/**
* @param args
*/
public static void main(String[] args) {
TestPost tp=new TestPost();
tp.searchDomainStatic();
}
public void searchDomainStatic(){
HttpPost httpost=null;
List<NameValuePair> nvps = new ArrayList <NameValuePair>();
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpResponse response = null;
HttpEntity entity=null;
try {
httpost = new HttpPost("这里是要登录网站form表单里的action跳转到的地址。如人民微博的是" +
"http://t.people.com.cn/login.action;jsessionid=D04CAC2D53CD6BEF7F05F025CBDCBDE4.node3");
} catch (URISyntaxException e) {
e.printStackTrace();
}
/*
* 下面是form表单里面的参数用户名密码之类的
*/
nvps.add(new BasicNameValuePair("userName", "fffff"));
nvps.add(new BasicNameValuePair("password", "fffff"));
nvps.add(new BasicNameValuePair("method", "post"));
nvps.add(new BasicNameValuePair("isremember", "true"));
nvps.add(new BasicNameValuePair("__checkbox_isremember", "true"));
try {
httpost.setEntity(new UrlEncodedFormEntity(nvps));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
httpost.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,10000);
response = httpclient.execute(httpost);
try {
//下面的是如果登陆成功后想跳转到的地址
HttpPost httpost1 =new HttpPost("下面的是如果登陆成功后想跳转到的地址");
response = httpclient.execute(httpost1);
entity = response.getEntity();
//下面是保存镜像文件,也可以理解为保存网页信息到本地
if(entity != null){
byte[] bytes=null;
try {
bytes = EntityUtils.toByteArray(entity);
DataOutputStream out = new DataOutputStream(new FileOutputStream("c://pen.htm"));
for (int i = 0; i < bytes.length; i++){
out.write(bytes[i]);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (URISyntaxException e) {
e.printStackTrace();
}
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}