《Android开发卷——HTTP网络通信,HTTP网络连接》

为了访问互联网,需要设置应用程序获取“androd.permission.INTERNET”权限的许可。


一、使用Apache接口(org.apache.http)并实现网络连接的基本知识


HttpClient client = new DefaultHttpClient();


要想从服务器检索有用的网络信息,必须使用HttpGet类构造器来帮助实现


HttpGet request = new HttpGet(http://www.*****.com/test?id=***&name=****);


然后还需要类HttpClientexecute()方法的帮助,通过此方法中的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实例,负责管理HttpClientHTTP连接。


在文件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());
}

尊重原创,转载请注明出处:http://blog.csdn.net/chillax_li/article/details/22078625


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值