HttpClient 用于HTTP GET 请求

HttpClient的使用模式:

1. 创建一个HttpClent

2.实例化新的HTTP方法,比如PostMethod 或 GetMethod

3.设置HTTP参数名称/值

4.使用HttpClent执行HTTP调用

5.处理Http响应

 

如下代码使用HttpClent获取HttpGet请求:

public class TestHttpGet {

	public String executeGet(String url) throws Exception {
		BufferedReader in = null;

		String content = null;
		try {
			// 定义HttpClient
			HttpClient client = new DefaultHttpClient();
			// 实例化HTTP方法
			HttpGet request = new HttpGet();
			request.setURI(new URI(url));
			HttpResponse response = client.execute(request);

			in = new BufferedReader(new InputStreamReader(response.getEntity()
					.getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			content = sb.toString();
		} finally {
			if (in != null) {
				try {
					in.close();// 最后要关闭BufferedReader
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return content;
		}
	}

	

}
 

你可能感兴趣的:(httpclient)