[Socket]利用Jatarka下HttpClient发送(Get && Post)请求

本文介绍如何使用Jakarta的org.apache.commons HttpClient库进行GET和POST请求。提供了一个自定义的参数类来封装请求参数,并分享了相关的HttpClient API参考资料。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

利用Jakarta的org.apache.commons下的HttpClient发送GET和POST请求,这是我自己写的一个工具类,记下来留着以后用,另附期帮助API(org.apache.commons.client.httpclient):

HttpClient APIs


1、首先,我们需要一个参数类,用类封装发送Http请求时的参数集合,该类就是一个请求参数的键值对,代码如下:

package com.mars.model;

import java.io.Serializable;

public class Parameter implements Serializable, Comparable<Parameter> {

	private static final long serialVersionUID = 2721340807561333705L;

	private String name;
	private String value;

	public Parameter() {
		super();
	}

	public Parameter(String name, String value) {
		super();
		this.name = name;
		this.value = value;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	@Override
	public boolean equals(Object obj) {
		//对象不为空
		if (obj == null) {
			return false;
		}
		//hashCode相等
		if (this == obj) {
			return true;
		}

		if (obj instanceof Parameter) {
			Parameter param = (Parameter) obj;
			return this.getName().equals(param.getName())
					&& this.getValue().equals(param.getValue());
		}

		return false;
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return super.toString();
	}

	@Override
	public int compareTo(Parameter arg0) {
		// TODO Auto-generated method stub
		return 0;
	}

}

2、然后我们新建一个HttpUtils类,发送Http请求分为同步和异步两种方式,这是我只是用的同步方式,异步我暂时不太熟悉,代码如下:

package com.mars.util;

import java.io.InputStream;
import java.util.List;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.mars.model.Parameter;

public class SyncHttp {

	private static final Log LOG = LogFactory.getLog(SyncHttp.class);
	private static final int CONNECTION_TIME = 1000 * 5;

	/**
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	public String httpGet(String url, String params) {
		// 创建HttpClient
		// 创建HttpMethod
		// 设置超时
		// 执行HttpMethod
		// 判断返回的状态码
		// 成功,则获取HttpMethod的InputStream
		String response = "";
		if (!params.equals("") && params != null) {
			url = url + "?" + params;
		}
		HttpClient client = new HttpClient();
		GetMethod getMethod = new GetMethod(url);
		getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,
				CONNECTION_TIME);
		try {
			int statusCode = client.executeMethod(getMethod);
			if (statusCode == HttpStatus.SC_OK) {
				InputStream in = getMethod.getResponseBodyAsStream();
				response = getData(in);
			} else {
				LOG.debug("Get Method StatusCode:" + statusCode);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			getMethod.releaseConnection();
			client = null;
		}
		return response;
	}

	public String httpPost(String url, List<Parameter> params) throws Exception {
		String response = "";
		HttpClient client = new HttpClient();
		PostMethod postMethod = new PostMethod();
		postMethod.addParameter("Connection", "Keep-Alive");
		postMethod.addParameter("Charset", "UTF-8");
		postMethod.addParameter("Content-Type",
				"application/x-www-form-urlencoded");
		postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,
				CONNECTION_TIME);
		if (!params.equals("") && params != null) {
			postMethod.setRequestBody(buildNameValuePair(params));
		}
		int statusCode = client.executeMethod(postMethod);
		if (statusCode == HttpStatus.SC_OK) {
			InputStream in = postMethod.getResponseBodyAsStream();
			response = this.getData(in);
		} else {
			LOG.debug("Post Method StatusCode:" + statusCode);
		}
		postMethod.releaseConnection();
		client = null;
		return response;
	}

	/**
	 * 封装HttpPost的Name-Value参数对
	 * 
	 * @param list
	 * @return
	 */
	private NameValuePair[] buildNameValuePair(List<Parameter> list) {
		int length = list.size();
		NameValuePair[] pais = new NameValuePair[length];
		for (int i = 0; i < length; i++) {
			Parameter param = list.get(i);
			pais[i] = new NameValuePair(param.getName(), param.getValue());
		}
		return pais;
	}

	/**
	 * 
	 * @param in
	 * @return
	 * @throws Exception
	 */
	private String getData(InputStream in) throws Exception {
		StringBuffer sb = new StringBuffer();
		int len = -1;
		byte[] bytes = new byte[1024];

		while ((len = in.read(bytes)) != -1) {
			sb.append(new String(bytes));
		}
		String data = sb.toString();
		return data;
	}
}

OK,以上两个类就完成了,此文是我自己备份的代码,建议大家也做一个自己的代码库,因为我发现这样的效果非常不错,对今后的工作有很大的帮助。

转载请标明出处,zanbiyaJJ@163.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值