给一个url获得后台的数据

importorg.apache.http.client.CloseableHttpResponse;

//1、获得HttpClient的操作对象

CloseableHttpClient httpClient =HttpClient.createDefault();

//2、准备url

String url = “http://www.baibu.com”;

//3、确定请求类型 – get post

HttpGet httpget = new HttpGet(url);

//4、发送请求

CloseableHttpResponse response =httpClient.execute(httpget);

 

//解析响应

//判断响应的状态码,200表示成功。

if(response.getStatusLine().getStatusCode()== 200){

HttpEntity entity =response.getEntity();

//它:

//String result = EntityUtils.toString(entity);

//System.out.println(result);

 

//或者它:

//获得响应流

InputStream content =entity.getContent();

//转换流

Reader reader = newInputStreamReader(content);

StringWriter sw = newStringWriter();

char[] buffer = new char[1024*8];

int len = 0;

while(len = reader.read(buffer) !=-1){

     sw.write(buffer,0,len);

}

//打印结果

String result=sw.getBuffer().toString();

System.out.println(result);

content.close();

sw.close();

}

你可能感兴趣的:(给一个url获得后台的数据)