除了通过标准的Java接口来实现android应用的联网操作(适用于简单的网络访问),Apache提供了HttpClient,它对java.net中的类做了封装和抽象,更适合android上开发联网应用,注意一定别忘了加权限,另外4.0的系统中网络访问不能在主线程中进行,不然会报异常。
1.HttpClient Get方式访问网络
HttpGet httpGet = new HttpGet(url);
HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String strResult = EntityUtils.toString(httpResponse
.getEntity());
//InputStream inputStream = httpResponse.getEntity().getContent();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
这里我们得到了输入流和字符串,需要注意的是这两个方法不能同时使用,不然会报非法状态异常。
此外可以设置连接的一些属性,如连接超时等,在DefaultHttpClient的构造方法中将这个参数传入:
HttpParams params = new BasicHttpParams();
// 设置一些基本参数
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params,
CHARSET);
HttpProtocolParams.setUseExpectContinue(params, true);
HttpProtocolParams
.setUserAgent(
params,
"Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
+ "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
// 超时设置
/* 从连接池中取连接的超时时间 */
ConnManagerParams.setTimeout(params, 1000);
/* 连接超时 */
HttpConnectionParams.setConnectionTimeout(params, 2000);
/* 请求超时 */
HttpConnectionParams.setSoTimeout(params, 4000);
// 设置我们的HttpClient支持HTTP和HTTPS两种模式
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
schReg.register(new Scheme("https", SSLSocketFactory
.getSocketFactory(), 443));
// 使用线程安全的连接管理来创建HttpClient
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
params, schReg);
customerHttpClient = new DefaultHttpClient(conMgr, params);
有时需要进行多次联网尝试,可在最外层加个循环,设定尝试连接的最大次数:
HttpGet httpGet = new HttpGet(url);
HttpClient httpClient = new DefaultHttpClient();
int time = 0;
final int RETRY_TIME = 3;
do {
try {
System.out.println(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println(httpResponse.getStatusLine().getStatusCode());
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String strResult = EntityUtils.toString(httpResponse
.getEntity());
System.out.println(strResult);
//inputStream = httpResponse.getEntity().getContent();
}
break;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
time++;
if(time<RETRY_TIME){
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
continue;
}
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
time++;
if(time<RETRY_TIME){
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
continue;
}
e.printStackTrace();
}
} while (true);
2.HttpClient Post方式访问网络
// httpclientPost获取数据
void PostTest() {
HttpPost post = new HttpPost("http://www.baidu.com");
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("name", "abc"));
try {
post.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
System.out.println(EntityUtils.toString(response.getEntity()));
}
}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO: handle exception
} catch (Exception e) {
// TODO: handle exception
}
}
3.java.net包的http连接
// http连接获取数据
protected void getPhpData() {
String urlStr = "";
URL url;
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
url = new URL(urlStr);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
StringBuffer temp = new StringBuffer();
while ((line = reader.readLine()) != null) {
temp.append(line);
}
line = temp.toString();
Log.e("-----------------------", "-----------------------");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}