关于HttpClient的使用

1.如果应用程序需要执行多个HTTP调用,则应该创建一个为所有HTTP请求服务的HttpClient,可以将HttpClient关联到Android的应用程序对象中

2.HttpClient同时发出多个请求可能引起的多线程问题,可以使用ThreadSafeClientConnManager创建DefaultHttpClient

主要代码:

public class ApplicationHc extends Application{private static final String TAG = "ApplicationHc";private HttpClient httpClient;@Overridepublic void onCreate() {super.onCreate();httpClient = createHttpClient();}@Overridepublic void onLowMemory() {super.onLowMemory();shutdownHttpClient();}@Overridepublic void onTerminate() {super.onTerminate();shutdownHttpClient();}//创建HttpClient对象private HttpClient createHttpClient(){Log.i(TAG, "Create HttpClient...");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(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));schReg.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);return new DefaultHttpClient(conMgr,params);}//关闭HttpClentprivate void shutdownHttpClient(){if(httpClient !=null && httpClient.getConnectionManager()!=null){httpClient.getConnectionManager().shutdown();}}public HttpClient getHttpClient(){return httpClient;}}

在Activity中使用:

private String getHttpContent(){String con = null;try{ApplicationHc  app= (ApplicationHc)this.getApplication();HttpClient client = app.getHttpClient();HttpGet get = new HttpGet();get.setURI(new URI("http://www.google.com/ig/api?weather=Guangzhou"));HttpResponse response = client.execute(get);con = EntityUtils.toString(response.getEntity());}catch (Exception e) {e.printStackTrace();}return con;}

修改AndroidManifest.xml

<application android:icon="@drawable/icon" android:label="@string/app_name" android:name= ".ApplicationHc">

更多相关文章

  1. Android(安卓)Studio(一)介绍
  2. android 6.0sd卡内部存储 & 外部存储
  3. Activity and Task(一)
  4. Android(安卓)使用OKHttp获取字符串和下载图片
  5. 6.腾讯微博Android客户端开发——换取Access Token
  6. Android结合ButterKnife创建自己的BaseActivity(兼容6.0)
  7. 第2.3节 android目录中manifest的介绍
  8. Android(安卓)Studio--活动创建&简单布局
  9. android发送http请求—-URLConnection、HttpURLConnection的使用

随机推荐

  1. android开发视频资源 电驴10G下载
  2. android 动态注册 广播
  3. 菜单 Android Menu
  4. android之activity全面解析
  5. Android遇到的问题解决方法
  6. Android: 自定义窗口大小
  7. Svg标签跟学习
  8. Android Activity生命周期和状态
  9. android 多个按钮中一个高亮
  10. android 多线程实现方式、并发与同步学习