存檔一份使用commons-httpclient發送請求的代碼片斷,為了大象越來越衰弱的記憶力,像這種不經常使用,但在某個需要的時刻又想不起來的情況。
代碼里的commons-httpclient是3.1版本,沒有任何技術含量,所以代碼也沒寫注釋,放在博客上面是為了大象方便查找^_^,各位親直接無視吧。
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發送請求
* @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;
}
}
本文為菠蘿大象原創,如要轉載請注明出處。http://www.tkk7.com/bolo
posted on 2013-11-05 16:20
菠蘿大象 閱讀(2944)
評論(0) 編輯 收藏 所屬分類:
Java