HTTPCLIENT是模拟浏览器请求的APACHE下HTTPCOMPENT下的一个组件,前段时间写一个免登陆程序,尝试用到了这个组件,部分代码如下:
HttpClient client = new HttpClient();//打开个浏览器
Get提交:
String url = http://www.163.com;
GetMethod getMethod = new GetMethod(url);//输入GET请求的URL
int statusCode = httpClient.executeMethod(getMethod);//回车
if(statusCode==200){
String str = getMethod.getResponseBodyAsString();//得到URL请求页面的HTML源码
str = EncodingZH.isoToOtherCharset(str,“gbk”);//可能出现页面乱码,自己写个字符集转换即可 return str;
}else{
System.out.println("error status:"+statusCode);
return null;
}
POST提交:
String url = http://www.xxx.com/register.jsp;
PostMethod postMethod = new PostMethod(url);//输入POST请求的URL
NameValuePair[] postParam = new NameValuePair[2];//设置表单中的参数
postParam[0]=new NameValuePair("username","${username}");//用户名-在页面上输入的用户名 postParam[1]=new NameValuePair("password","${password}");//同上 postMethod.addParameters(pairs);
int statusCode = httpClient.executeMethod(postMethod);
if(statusCode==200){
String str = getMethod.getResponseBodyAsString();//得到URL请求页面的HTML源码
str = EncodingZH.isoToOtherCharset(str,“gbk”);//可能出现页面乱码,自己写个字符集转换即可 return str;
}else{
System.out.println("error status:"+statusCode);
return null;
}