容易的httpClient访问

简单的httpClient访问

1、下载 httpcomponents-client-4.1.1
2、在eclipse中导入htttpClient的jar   

 

首先模拟http请求头:
 HttpGet httpost = new HttpGet("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(httpget);

			Header[] hs = response.getAllHeaders();
			for(Header h:hs) {
				System.out.println(h.getName()+"   "+h.getValue());
			}

		} catch (Exception e) {
			//发送请求时 错误
			e.printStackTrace();
		}

        //获取响应内容
        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);
	    		    	}
	    		    	System.out.println(sb.toString());
	        }
         } catch (Exception ex) {
        	 if(httpget.isAborted())
            	httpget.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();
 

 

 

1 楼 SVFdnhbfsdn 2011-11-02  
容易的httpClient访问
2 楼 君心可晴 2012-01-02  
容易的httpClient访问 lz学习了,灰常感谢容易的httpClient访问