可以模拟浏览器的get请求和post请求,需要的包请搜索下载commons-httpclient.jar
package test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import com.xdatasystem.contactsimporter.UpdateableCookieStore;
public class HTTPUtil {
/**
* 简单的get 请求
* @param url
* @return
*/
public static String httpSimpleGet(String url){
String result = null;
DefaultHttpClient client =new DefaultHttpClient();
HttpGet get=new HttpGet(url);
HttpParams params=client.getParams();
HttpConnectionParams.setConnectionTimeout(params, 10000);//设置请求超时时间为10秒
HttpResponse response=null;
try{
response=client.execute(get);
HttpEntity entity=response.getEntity();//得到http的内容
result=EntityUtils.toString(entity);
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
if(client!=null){
client.getConnectionManager().shutdown();
}
}
return result;
}
//带参数的get请求
public static String httpGet(String url,Map params){
if(params!=null){
StringBuffer buffer=new StringBuffer(url);
buffer.append("?");
Set<String> keys=params.keySet();
Iterator it=keys.iterator();
while(it.hasNext()){
String key=(String) it.next();
buffer.append(key);
buffer.append("=");
buffer.append(params.get(key));
buffer.append("&"); }
url=buffer.toString();
}
System.out.println(url);
String result = null;
DefaultHttpClient client =new DefaultHttpClient();
HttpGet get=new HttpGet(url);
HttpParams clientParams=client.getParams();
HttpConnectionParams.setConnectionTimeout(clientParams, 10000);//设置请求超时时间为10秒
HttpResponse response=null;
try{
response=client.execute(get);
HttpEntity entity=response.getEntity();//得到http的内容
result=EntityUtils.toString(entity);
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
if(client!=null){
client.getConnectionManager().shutdown();
}
}
return result;
}
/**
* post请求
*/
public static String httpPost(String reqUrl,Map reqParams) throws ClientProtocolException, IOException{
String result=null;
DefaultHttpClient client;
client = new DefaultHttpClient();
client.setCookieStore(new UpdateableCookieStore());
//以下注释的内容是添加初始的cookie信息
// BasicClientCookie clientCookie = new BasicClientCookie("", "0.01" + System.currentTimeMillis());
// clientCookie.setDomain(".126.com");
// clientCookie.setPath("/");
// client.getCookieStore().addCookie(clientCookie);
//构建参数集合,
ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
//请求必须的参数
if(reqParams!=null){
Set<String> keys=reqParams.keySet();
Iterator it=keys.iterator();
while(it.hasNext()){
String key=(String) it.next();
params.add(new BasicNameValuePair(key, (String) reqParams.get(key)));
}
}
//构建http头
List headers = new ArrayList();
headers.add(new BasicHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; CIBA; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"));
client.getParams().setParameter("http.default-headers", headers);
HttpPost post = new HttpPost(reqUrl);
post.addHeader("Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/x-ms-application, application/x-ms-xbap,
application/vnd.ms-xpsdocument, application/xaml+xml, */*");
post.addHeader("Accept-Language", "zh-cn");
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
post.addHeader("Accept-Encoding", "ISO-8859-1,utf-8;gbk;default");
post.addHeader("Host", reqUrl);
post.addHeader("Cache-Control", "no-cache");
post.addHeader("Connection", "Keep-Alive");
post.addHeader("UA-CPU", "x64");
post.addHeader("Referer", reqUrl);//链接到reqUrl时所在的页面,某些网站可以不做设置
post.setEntity(new UrlEncodedFormEntity(params, "gbk"));
HttpProtocolParams.setUseExpectContinue(client.getParams(), false);
HttpProtocolParams.setUseExpectContinue(post.getParams(), false);
//发送post请求
HttpResponse resp = client.execute(post);
InputStream content = null;
try {
//得到输入流
content = resp.getEntity().getContent();
try {
// 获取返回信息
BufferedReader in = new BufferedReader(new InputStreamReader(
content, "GB2312"));
StringBuffer buffer = new StringBuffer();
String line;
while ((line = in.readLine()) != null) {
buffer.append(line).append("\n");
}
// 输出获取的信息
result = buffer.toString();
System.out.println(result);
// 获取cookie
List<Cookie> cs = client.getCookieStore().getCookies();
for (Cookie cookie : cs) {
System.out.println("name:" + cookie.getName() + ",value="
+ cookie.getValue());
}
} finally {
if (content != null) {
content.close();
}
}
return result;
} catch (Exception e) {
e.printStackTrace();
return result;
}
}
}