HttpClient4登陆ITeye

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);
		}
	}
}

猜你喜欢

转载自caerun.iteye.com/blog/1337784
今日推荐