利用Jakarta的org.apache.commons下的HttpClient發送GET和POST請求,這是我自己寫的一個工具類,記下來留着以後用,另附期幫助API(org.apache.commons.client.httpclient):
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,以上兩個類就完成了,此文是我自己備份的代碼,建議大家也做一個自己的代碼庫,因爲我發現這樣的效果非常不錯,對今後的工作有很大的幫助。
轉載請標明出處,[email protected]