HttpClient请求数据,代码如下:
String url = "http://www.baidu.com";
String xmlString = getXmlString(url);
public static InputStream getXmlString(String url) {
// TODO Auto-generated method stub
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
try {
HttpResponse httpResponse = client.execute(get);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
//返回数据流
InputStream content = httpResponse.getEntity().getContent();
//返回字符串
// String str = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
return content;
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
HtupUrlConnection请求数据,代码如下:
String url = "http://www.baidu.com";
//调用如下
getJsonData(url);
public static InputStream getJsonData(String url) {
try {
URL urls = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urls.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.connect();
// 判断是否正常响应数据
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
return conn.getInputStream();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}