ITeye博客

简单的httpclient的例子

fainily · 2014-01-15 13:57 · java · 编程语言 · Markdown


private String searchByHttp(String httpAddress){
		String rel = "";
		// 创建HttpClient实例     
		HttpClient httpclient = new DefaultHttpClient();  
		try {

		   
		        // 创建Get方法实例     
		        String address =  httpAddress;
		        HttpGet httpgets = new HttpGet(address); 
		        HttpConnectionParams.setConnectionTimeout(httpgets.getParams(), 5000);  
		       
		        HttpResponse response = null;
				response = httpclient.execute(httpgets);
		        HttpEntity entity = response.getEntity();    
			        if (entity != null) {    
			            InputStream instreams = entity.getContent();
			            rel = convertStreamToString(instreams);  
		//		            System.out.println(rel);  
			            // Do not need the rest    
			            httpgets.abort();    
			        }
        } catch (ConnectTimeoutException e) {
			e.printStackTrace();
			rel = "连接超时";
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
		finally{
			httpclient.getConnectionManager().shutdown();  
		}
		return rel;
	}
	
	private  String convertStreamToString(InputStream is) {      
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));      
        StringBuilder sb = new StringBuilder();      
        String line = null;      
        try {      
            while ((line = reader.readLine()) != null) {  
                sb.append(line + "\n");      
            }      
        } catch (IOException e) {      
            e.printStackTrace();      
        } finally {      
            try {      
                is.close();      
            } catch (IOException e) {      
               e.printStackTrace();      
            }      
        }      
        return sb.toString();      
    }  


评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。