这个实例中只介绍发送get请求并获取返回值的代码

package com.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;


import org.apache.http.Header;
import org.apache.http.HttpEntity;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class Test {

	public static void main(String[] args) throws Exception {
		String url = "http://www.wangerbao.com/?p=874";
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(url);
		CloseableHttpResponse response = httpclient.execute(httpGet);
		System.out.println(getLineStringByResponse(response));
		System.out.println();
		System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
		System.out.println(getHeadStringByResponse(response));
		System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
		System.out.println(getBodyStringByResponse(response));
		
		
		
		//释放连接
		httpGet.releaseConnection();
		httpclient.close();
	}
	
	public static String getLineStringByResponse(CloseableHttpResponse response){
		String line = response.getStatusLine().toString();
		return line;
	}
	
	/**
	 * 获取Response的Header
	 * */
	public static String getHeadStringByResponse(CloseableHttpResponse response){
		Header header[] = response.getAllHeaders();
		String str = "";
		for(int i = 0;i < header.length;i++){
			str = str + header[i].getName()+":"+header[i].getValue()+"\r\n";
		}
		return str;
	}
	
	/**
	 * 获取Response的Body
	 * */
	public static String getBodyStringByResponse(CloseableHttpResponse response){
		HttpEntity entity = response.getEntity();
		InputStream is = null;
		BufferedReader in = null;
		StringBuffer buffer = new StringBuffer();
		String line = "";
		try {
			is = entity.getContent();
			in = new BufferedReader(new InputStreamReader(is));
			while ((line = in.readLine()) != null) {
				buffer.append(line).append("\t\n");
			}
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				in.close();
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return buffer.toString();
	}

}

发表评论

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