HTTPClient4的典型小例子

1.简单的获取一个HTML页面的内容

package com.bijian.study;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpClientGetHtmlDemo {

	public static void main(String[] args) throws Exception {
		HttpClientGetHtmlDemo httpClientDemo = new HttpClientGetHtmlDemo();
		httpClientDemo.getHTML();
	}
	
	/**
	 * 简单的获取一个HTML页面的内容
	 * @throws Exception
	 */
	public void getHTML() throws Exception {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpGet httpget = new HttpGet("http://www.baidu.com/");
		HttpResponse response = httpclient.execute(httpget);
		HttpEntity entity = response.getEntity();
		String html = EntityUtils.toString(entity);
		System.out.println(html);
		httpclient.close();
	}
}

 

2.下载一个图片到本地

package com.bijian.study;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class HttpClientDownloadFileDemo {

	public static void main(String[] args) throws Exception {
		
		HttpClientDownloadFileDemo httpClientDemo = new HttpClientDownloadFileDemo();
		
		httpClientDemo.downloadFile();
	}
	
	/**
	 * 下载一个图片到本地
	 * @throws Exception
	 */
	public void downloadFile() throws Exception {
		// 图片的网址
		String url = "http://ww2.sinaimg.cn/large/9d57a855jw1dqpv9fp4yuj.jpg";

		String destfilename = "D:\\cat.jpg";
		// 生成一个httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();

		HttpGet httpget = new HttpGet(url);
		HttpResponse response = httpclient.execute(httpget);
		HttpEntity entity = response.getEntity();
		InputStream in = entity.getContent();
		File file = new File(destfilename);
		try {
			FileOutputStream fout = new FileOutputStream(file);
			int l = -1;
			byte[] tmp = new byte[1024];
			while ((l = in.read(tmp)) != -1) {
				fout.write(tmp, 0, l);
			}
			fout.flush();
			fout.close();
		} finally {
			// 关闭低层流。
			in.close();
		}
		httpclient.close();
	}
}

        运行结束后,我们可以到D盘下看到cat.jpg,打开即可看到这只可爱又漂亮的猫。



3.post模拟人人网登陆

package com.bijian.study;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClientLoginDemo {
	private CloseableHttpClient httpclient;
	private HttpPost httppost;// 用于提交登陆数据
	private HttpGet httpget;// 用于获得登录后的页面
	private String login_success;// 用于构造上面的HttpGet

	public HttpClientLoginDemo() {
		httpclient = HttpClients.createDefault();
		// 人人的登陆界面网址
		httppost = new HttpPost("http://www.renren.com/PLogin.do");
	}

	public void logIn(String name, String password) throws Exception {
		// 打包将要传入的参数
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("email", name));
		params.add(new BasicNameValuePair("password", password));
		httppost.setEntity(new UrlEncodedFormEntity(params));
		try {
			// 提交登录数据
			HttpResponse re = httpclient.execute(httppost);
			// 获得跳转的网址
			Header locationHeader = re.getFirstHeader("Location");
			// 登陆不成功
			if (locationHeader == null) {
				System.out.println("登陆不成功,请稍后再试!");
				return;
			} else// 成功
			{
				login_success = locationHeader.getValue();// 获取登陆成功之后跳转链接
				System.out.println("成功之后跳转到的网页网址:" + login_success);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void PrintText() throws IOException {
		httpget = new HttpGet(login_success);
		HttpResponse re2 = null;

		try {
			re2 = httpclient.execute(httpget);
			// 输出登录成功后的页面
			String str = EntityUtils.toString(re2.getEntity());
			System.out.println(str);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			httppost.abort();
			httpget.abort();
			httpclient.close();
		}
	}

	public static void main(String[] args) throws Exception {
		
		String name = "username", password = "password";
		// 自己的账号,口令
		HttpClientLoginDemo httpClientLoginDemo = new HttpClientLoginDemo();
		httpClientLoginDemo.logIn(name, password);
		httpClientLoginDemo.PrintText();
	}
}

        如果账号密码不对,程序执行结果好像是对的,但稍加看下输出的内容,其实只是做了页面跳转。

 

文章来源:http://my.oschina.net/v5871314/blog/204812?fromerr=FPgwXe9e

你可能感兴趣的:(httpclient4)