您的位置:首页 > 理论基础 > 计算机网络

Commons-httpclient的使用技巧,更方便的模拟http请求!

2011-06-16 10:41 337 查看
本文来自:http://lavasoft.blog.51cto.com/62575/168276/

另外一个好文章:

http://www.blogjava.net/willpower88/archive/2008/04/14/192679.html

需要jar包:

common-codec

common.httpclient

public static void main(String[] args) {
//请求地址
String url = "http://localhost:8080/moneyManager/game";
doGet(url);
Map<String,String> params = new HashMap<String,String>();
params.put("gameName", "仙剑奇侠传5");
params.put("clickCount", "4");
//String str = doPost(url,params);
//System.out.println(str);
}
public static void  doGet(String url){
String queryString = "";
String response = null;
HttpClient client = new HttpClient();
//防止乱码
client.getParams().setParameter(
HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
//设置编码的三种方式
//postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
//postMethod.addRequestHeader("Content-Type","text/html;charset=UTF-8");
//postMethod.setRequestHeader("Content-Type", "text/html;charset=UTF-8");

HttpMethod method = new GetMethod(url);
try {
if (queryString!=null&&!"".equals(queryString))
method.setQueryString(URIUtil.encodeQuery(queryString));
//method.set
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_OK) {
response = method.getResponseBodyAsString();
}
} catch (URIException e) {
// log.error("执行HTTP Get请求时,编码查询字符串“" + queryString + "”发生异常!", e);
} catch (IOException e) {
//log.error("执行HTTP Get请求" + url + "时,发生异常!", e);
} finally {
method.releaseConnection();
}
System.out.println(response);
}

public static String doPost(String url, Map<String, String> params) {
String response = null;
HttpClient client = new HttpClient();
HttpMethod method = new PostMethod(url);
for (Iterator it = params.entrySet().iterator(); it.hasNext();) {

}
//设置Http Post数据
if (params != null) {
HttpMethodParams p = new HttpMethodParams();
for (Map.Entry<String, String> entry : params.entrySet()) {
p.setParameter(entry.getKey(), entry.getValue());
}
method.setParams(p);
}
try {
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_OK) {
response = method.getResponseBodyAsString();
}
} catch (IOException e) {
//log.error("执行HTTP Post请求" + url + "时,发生异常!", e);
System.out.println("执行HTTP Post请求" + url + "时,发生异常!");
} finally {
method.releaseConnection();
}

return response;
}


注意代码中设置编码,防止出现乱码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: