Android 程序访问WEB服务 HTTP 接口使用
本文基于Android 2.3平台讲解,尤其注意的是Httpclient方法使用的Apache 接口和方法在2.3平台以后有变动。
1、HttpClient方式
private static ClientConnectionManager sClientConnectionManager = null; public final ConnPerRoute sConnPerRoute = new ConnPerRoute() { public int getMaxForRoute(HttpRoute route) { return 80; } }; public synchronized ClientConnectionManager getClientConnectionManager() { if (sClientConnectionManager == null) { // Create a registry for our three schemes; http and https will // use // built-in factories SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory .getSocketFactory(), 80)); // And create a ccm with our registry HttpParams params = new BasicHttpParams(); params .setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 320); params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, sConnPerRoute); sClientConnectionManager = new ThreadSafeClientConnManager(params, registry); } // Null is a valid return result if we get an exception return sClientConnectionManager; } private HttpClient getHttpClient(int timeout) { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 20 * 1000); HttpConnectionParams.setSoTimeout(params, timeout); HttpConnectionParams.setSocketBufferSize(params, 8192); HttpClient client = new DefaultHttpClient(getClientConnectionManager(), params); return client; } HttpClient client = getHttpClient(20 * 1000); HttpGet method = new HttpGet("http://**.com/xx"); method.setHeader("Connection", "keep-alive"); HttpResponse res = client.execute(method); int code = res.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { HttpEntity e = res.getEntity(); ......//BODY处理 }
2、HttpURLConnection
String url = "http://**.com/xx"; URL myFileURL = null; HttpURLConnection conn = null; Proxy proxy = null; boolean needProxy = false; private boolean getNetType() { ConnectivityManager conn = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); if (conn == null) { Log.v("tag", "@==============data is disconnecting="); return false; } NetworkInfo info = conn.getActiveNetworkInfo(); if (info == null) return false; String type = info.getTypeName();// MOBILE(GPRS);WIFI Log.v("tag", "@==============NetworkType=" + type); if (type.equalsIgnoreCase("WIFI")) { return true; } else if (type.equalsIgnoreCase("MOBILE")) { String apn = info.getExtraInfo(); Log.v("tag", "@============APN=" + apn); if (apn != null && apn.equalsIgnoreCase("cmwap")) { return false; } else { return true; } } return false; } // 当我们使用的是中国移动的手机网络时,下面方法可以直接获取得到10.0.0.172,80端口 if (!getNetType()) { needProxy = true; String host = android.net.Proxy.getDefaultHost(); // 通过andorid.net.Proxy可以获取默认的代理地址 int port = android.net.Proxy.getDefaultPort(); // 通过andorid.net.Proxy可以获取默认的代理端口 SocketAddress sa = new InetSocketAddress(host, port); // 定义代理,此处的Proxy是源自java.net proxy = new Proxy(java.net.Proxy.Type.HTTP, sa); } try { myFileURL = new URL(url); // 获得连接 if (needProxy) { conn = (HttpURLConnection) myFileURL.openConnection(proxy); needProxy = false; } else { conn = (HttpURLConnection) myFileURL.openConnection(); // 设置超时时间为6000毫秒,conn.setConnectionTiem(0);表示没有时间限制 } conn.setConnectTimeout(30000); // 连接设置获得数据流 // conn.setReadTimeout(5000); // conn.setDoInput(true); // 不使用缓存//这句好像不能用,不连CMNET都无法访问了 conn.setUseCaches(false); // 这句可有可无,没有影响 conn.setRequestMethod("GET"); conn.setRequestProperty("Connection", "close"); // conn.connect(); // 得到数据流 InputStream is = conn.getInputStream(); ......//BODY处理 }
中国移动对CMWAP作了一定的限制,主要表现在CMWAP接入时只能访问GPRS网络内的IP(10.*.*.*),而无法通过路由访问Internet。(少数地区的移动网络可能不存在这一限制。)我们用CMWAP浏览Internet上的网页就是通过WAP网关协议或它提供的HTTP代理服务实现的.所以在使用HttpURLConnection的时候要先进行接入模式判断,如果是CMWAP模式则要进行代理设置,而HttpClient不需要我们进行代理设置,我觉得应该是apache JAR包内帮我们进行这一判断。
参考: