为了访问互联网,需要设置应用程序获取“androd.permission.INTERNET”权限的许可。
一、使用Apache接口(org.apache.http)并实现网络连接的基本知识
HttpClient client = new DefaultHttpClient();
要想从服务器检索有用的网络信息,必须使用HttpGet类构造器来帮助实现
HttpGet request = new HttpGet(“http://www.*****.com/test?id=***&name=****”);
然后还需要类HttpClient的execute()方法的帮助,通过此方法中的HttpGet对象来检索
HttpResponse response = client.execute(request);
最后需要解读已检索的响应(读取网页内容)
BufferedReader rd = new BufferedRreader(new InputStreamReader(response.getEntity().getContent()));
String line = “”;
While((line = rd.readLine()) != null){
Log.d(“output:”,line);
line = line+line;
}
Post方法
HttpClient client = new DafaultHttpClient(); HttpPost post = new HttpPost(URL); List<NameValuePair> parms = new ArrayList<NameValuePair>(); parms.add(new NameValuePair(“id”,”1001”)); parms.add(new NameValuePair(“name”,”johm”)); HttpEntity formEntity = new UrlEncodeFormEntity(params); post.setEntity(formEntity,HTTP.UTF_8); Httpresponse response = new client.execute(post); If(response.getStatusLine.getStatusCode == HttpStatus.SC_OK){ InputStream is = response.getEntity().getContent(); String result = isStreamString(is); Assert.assertEqualse(result,”POST_SUCCESS”);//断言判断网页返回的内容是否为” POST_SUCCESS”; } private String isStreamString(InputStream is) throws Exception{ ByteArrayOutputStream bo = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int len = -1; while((len = is.read(buf)) != -1){ bo.write(buf,0,len); } return new String(bo.toByteArray()); }
在文件MyApplication.java中扩展了系统的Application:
public class MyApplication extends Application{ private HttpClient httpClient; public void onCreate(){ super.onCreate(); httpClient = this.createHttpClient(); } public void onLowMemory(){ super.onLowMemory(); this.shutdownHttpClient(); } public void onTerminamte(){ super.onTerminate(); this.shutdownHttpClient(); } //创建HttpClient实例 private HttpClient createHttpClient(){ HttpParams params = new BasicHttpParams(); HttpProtocolParams.setversion(params,HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params,HTTP.DEFAULT_CONTENT_CHARSET); HttpProtocolParams.setUseExpectContinue(params,true); SchemeRegistry schReg = new SchemeRegistry(); schReg.register(“http”,PlainSocketFactory.getSocketFactory(),80); schReg.register(“https”,SSLSocketFatory.getSocketFactory(),443); ClientConnectionManager connMgr = new ThreadSafeClientConnManager(params,schReg); return new DefaultHttpClient(connMgr,params); } //关闭连接管理器并释放资源 private void shutdownHttpClient(){ if(httpClient != null && httpClient.getConnectionManager() != null){ httpClient.getConnectionManager().shutdown(); } //对外提供HttpClient实例 public HttpClient getHttpClient(){ return httpClient; } }
在上述代码中重写了onCreate()方法,在系统启动时就创建一个HttpClient。
重写了onLowMemory()和onTerminate()方法,在内存不足和应用结束时关闭连接,释放资源。
需要注意的是,当实例化DefaultHttpClient时,传入一个由ThreadSafeClientConnManager创建的ClientConnectionManager实例,负责管理HttpClient的HTTP连接。
在文件AndroidManifest.xml中进行如下配置,目的是让“优化”版的Application生效。
<application android:name=”.MyApplication”…>…</application>
系统就会使用前面编写的MyApplication,然后就可以在context中调用getApplication()来获取MyApplication实例。
经过上面的“优化”处理配置,接下来就可以在活动中应用了
private void execute(){ try{ MyApplication app = (MyApplication) this.getApplication(); HttpClient client = app.getHttpClient(); HttpGet request = new HttpGet(“http://www.*****.com/test?id=***&name=****”); HttpResponse response = client.execute(request); if(response.getStatusLine.getStatusCode == HttpStatus.SC_OK){ InputStream is = response.getEntity().getContent(); String result = isStreamString(is); Toast.makeText(this,result,Toast.LENGTH_LONG).show(); } }catch(Exception e){ e.printStackTrace(); } } private String isStreamString(InputStream is) throws Exception{ ByteArrayOutputStream bo = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int len = -1; while((len = is.read(buf)) != -1){ bo.write(but,0,len); } return new String(bo.toByteArray()); }