简单的使用httpClient之远程请求获取数据

httpClient使用非常方便,远程请求url路径获取返回数据,数据类型可以是字符串,字节数组。httpClient顾名思义,实现了http协议的客户端。值得注意的是请求之后,一定要关闭请求。

import java.io.IOException;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.stereotype.Service;

import com.chinaedu.nstats.service.IServiceUtils;
@Service("serviceUtils")
public class ServiceUtils implements IServiceUtils {
	public String execute(String url){
		HttpClient httpClient  = new HttpClient();
		GetMethod getMethod = null;
		getMethod = new GetMethod(url);  
		String responseBody=null;
		try {
            int statusCode = httpClient.executeMethod(getMethod);
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Method failed: "
                        + getMethod.getStatusLine());
            }
            // 读取内容
            responseBody = getMethod.getResponseBodyAsString();
        } catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
        	getMethod.releaseConnection();
        }
		return responseBody;
		
	}
	public String executePostMethod(String url,Map<String,String> parames){
		HttpClient httpClient  = new HttpClient();
		PostMethod postMethod=null;
		postMethod = new PostMethod(url);  
		postMethod.addParameter("subject", parames.get("subject"));
		postMethod.addParameter("teacher", parames.get("teacher"));
		postMethod.addParameter("beginTime", parames.get("beginTime"));
		postMethod.addParameter("endTime", parames.get("endTime"));
		String responseBody=null;
		try {
            int statusCode = httpClient.executeMethod(postMethod);
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Method failed: "
                        + postMethod.getStatusLine());
            }
            // 读取内容
            responseBody = postMethod.getResponseBodyAsString();
        } catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			postMethod.releaseConnection();
        }
		return responseBody;
	}
}

猜你喜欢

转载自nicegege.iteye.com/blog/2202776