存檔一份使用commons-httpclient發(fā)送請(qǐng)求的代碼片斷,為了大象越來(lái)越衰弱的記憶力,像這種不經(jīng)常使用,但在某個(gè)需要的時(shí)刻又想不起來(lái)的情況。
代碼里的commons-httpclient是3.1版本,沒(méi)有任何技術(shù)含量,所以代碼也沒(méi)寫(xiě)注釋,放在博客上面是為了大象方便查找^_^,各位親直接無(wú)視吧。
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.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang.StringUtils;
/**
* 使用HttpClient發(fā)送請(qǐng)求
* @author 菠蘿大象
*/
public class HttpRequestClient {
public static String postRequest(String url, byte[] postData, String contentType) {
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(url);
ByteArrayRequestEntity bare = new ByteArrayRequestEntity(postData);
postMethod.setRequestHeader("Connection", "close");
postMethod.addRequestHeader("Content-Type",contentType+";charset=UTF-8");
postMethod.setRequestHeader("Content-Length", String.valueOf(bare.getContentLength()));
postMethod.setRequestEntity(new ByteArrayRequestEntity(postData));
httpClient.getParams().setBooleanParameter("http.protocol.expect-continue", false);
String result = StringUtils.EMPTY;
try {
httpClient.executeMethod(postMethod);
result = postMethod.getResponseBodyAsString();
postMethod.releaseConnection();
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
postMethod.releaseConnection();
if (httpClient != null) {
((SimpleHttpConnectionManager) httpClient.getHttpConnectionManager()).shutdown();
httpClient = null;
}
}
return result;
}
public static String postRequest(String url, Map<String, String> params, String contentType) {
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(url);
postMethod.setRequestHeader("Connection", "close");
postMethod.addRequestHeader("Content-Type",contentType+";charset=UTF-8");
for(Map.Entry<String, String> entry : params.entrySet()){
postMethod.addParameter(entry.getKey(), entry.getValue());
}
httpClient.getParams().setBooleanParameter("http.protocol.expect-continue", false);
String result = StringUtils.EMPTY;
try {
httpClient.executeMethod(postMethod);
result = postMethod.getResponseBodyAsString();
postMethod.releaseConnection();
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
postMethod.releaseConnection();
if (httpClient != null) {
((SimpleHttpConnectionManager) httpClient.getHttpConnectionManager()).shutdown();
httpClient = null;
}
}
return result;
}
}
本文為菠蘿大象原創(chuàng),如要轉(zhuǎn)載請(qǐng)注明出處。http://www.tkk7.com/bolo
posted on 2013-11-05 16:20
菠蘿大象 閱讀(2945)
評(píng)論(0) 編輯 收藏 所屬分類:
Java