1、下载 httpcomponents-client-4.1.1
2、在eclipse中导入htttpClient的jar
首先模拟http请求头:
HttpPost httpost = new HttpPost("http://www.baidu.com/");
//确定模拟浏览器的类型
httpost.addHeader("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.18) Gecko/20110614 Firefox/3.6.18");
//请求格式
httpost.addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8") ;
//请求刷新的地址
httpost.addHeader("Referer", " http://www.baidu.com/");
//请求的语种
httpost.addHeader("Accept-Language", "zh-cn");
//字符集信息
httpost.addHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");
//请求的主机
httpost.addHeader("Host", "www.baidu.com");
//连接信息
httpost.addHeader("Connection", "keep-alive");
添加请求参数:
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("username", "caisijia"));
nvps.add(new BasicNameValuePair("password", "12qwaszx"));
nvps.add(new BasicNameValuePair("getrand", "av1.v"));
//接受请求参数
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
发送请求 获取响应头
//建立http客户端
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response=null;
try {
//执行并且获取 响应头
response = httpclient.execute(httpost);
Header[] hs = response.getAllHeaders();
for(Header h:hs) {
System.out.println(h.getName()+" "+h.getValue());
}
} catch (Exception e) {
//发送请求时 错误
e.printStackTrace();
return null;
}
//获取响应内容
HttpEntity ent = response.getEntity();
InputStream instream=null;
BufferedReader reader = null;
try {
if (ent != null) {
instream = ent.getContent();
reader = new BufferedReader(
new InputStreamReader(instream));
StringBuilder sb =new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}
} catch (Exception ex) {
if(httpost.isAborted())
httpost.abort();
} finally {
try {
if(reader!=null)
reader.close();
if(instream!=null)
instream.close();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
httpclient.getConnectionManager().shutdown();
|