HttpClient4登陆ITeye

作者: wilsoncai 分类: httpclient 发布时间: 2018-01-06 01:07
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

public class Main {
	public static void main(String[] args) throws ClientProtocolException,
			IOException {
		HttpClient httpClient = new DefaultHttpClient();

		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		formparams.add(new BasicNameValuePair("name", "caiwenhn2008"));
		formparams.add(new BasicNameValuePair("password", "这个不能说"));
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams,
				"UTF-8");

		HttpPost httppost = new HttpPost("http://caerun.iteye.com/login");
		httppost.setEntity(entity);
		HttpContext localContext = new BasicHttpContext();

		HttpResponse response2 = httpClient.execute(httppost, localContext);
		int statusCode = response2.getStatusLine().getStatusCode();
		System.out.println("statusCode:" + statusCode);
		System.out.println(EntityUtils.toString(response2.getEntity(),"UTF-8"));
		EntityUtils.consume(response2.getEntity());
		
		
		if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
				|| statusCode == HttpStatus.SC_MOVED_TEMPORARILY
				|| statusCode == HttpStatus.SC_SEE_OTHER
				|| statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {
			String newUrl = response2.getLastHeader("Location").getValue();
			System.out.println("从新定向的页面为:" + newUrl);

			HttpGet get = new HttpGet(newUrl);
			HttpEntity entity2 = httpClient.execute(get, localContext)
					.getEntity();
			System.out.println(EntityUtils.toString(entity2,"UTF-8"));
			
			EntityUtils.consume(entity2);
		}
	}
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注