Httpclient基本用法

/**   

* @param url   
* @return   
* @throws Exception   
*/   
private String getContent(String url) throws Exception{    
    StringBuilder sb = new StringBuilder();    
        
    HttpClient client = new DefaultHttpClient();    ////获取一个默认的HttpClient的对象实现
    HttpParams httpParams = client.getParams();   //得到一参数对象,这个对象能够设置一些http请求的参数
    //设置网络超时参数    
    HttpConnectionParams.setConnectionTimeout(httpParams, 3000);   //看不懂么?超时,3s,也就是最多等待3s后就算是链接超时,不要再等待下去
    HttpConnectionParams.setSoTimeout(httpParams, 5000);   //这句话是socket超时设置,要知道http是基于socket的,socket不懂的可以找下资料学学
    HttpResponse response = client.execute(new HttpGet(url));   //这句话分成两部分:等号右边表示执行这个get请求,http分为get和post两种请求,这是个get.等号左边的意思是的到服务器的响应封装到对象response
    HttpEntity entity = response.getEntity();      //这句话是得到响应的内容,内容里面有很多信息

    if (entity != null) {

        //这句话是得到entity的内容啊,也就是返回对象的body,是一个输入流,用Buffer方式读取  

        BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"), 8192);    
          
        String line = null;    
        while ((line = reader.readLine())!= null){    
            sb.append(line + "\n");    
        }    
        reader.close();    
    }    
    return sb.toString();    

}  

 

posted @ 2013-11-07 14:48  道奇兔  阅读(516)  评论(0)    收藏  举报