http-android

1. android2.2以后建议使用HttpUrlConnection;

2. 获取http连接httpConnection = (HttpURLConnection) url.openConnection(proxy); HttpURLConnection为abstract, 具体类?

  a. 如果wifi可用,代理为null,不用代理: 

NetworkInfo ni = context.getSystemService(Context.CONNECTIVITY_SERVICE).getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (ni.isConnected()) ;

  b. 根据用户配置的apn:

Cursor c = context.getContentResolver().query(Uri.parse("content://telephony/carriers/preferapn"), null,null, null, null); //当前手机配置使用的apn

c.moveToFirst(); proxy = c.getString(c.getColumnIndex("proxy")); // 代理 port = c.getString(c.getColumnIndex("port")); // 端口 c.close();

new Proxy(Proxy.Type.HTTP, InetSocketAddress.createUnresolved(proxy, port));

new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxy, port));
  c. 写死proxy、port,用户的配置可能出错,根据不同的运营商写死不同的地址-端口

3. 配置请求参数, 作为http头部

  可上传: httpConnection.setDoOutput(true);
  可下载: httpConnection.setDoInput(true);
  Get或Post: httpConnection.setRequestMethod(method);
  cache: httpConnection.setUseCaches(false);
  重定向:httpConnection.setInstanceFollowRedirects(true);
  Post数据长度:httpConnection.setFixedLengthStreamingMode(postDataLenth); //enable streaming without buffering
  连接超时:httpConnection.setConnectTimeout(60 * 1000); //设为15s、60s等
  获取数据段数据超时:httpConnection.setReadTimeout(60 * 1000);

http规范中预定义的header:

  返回结果类型:httpConnection.setRequestProperty("Accept", "*/*");
  http-alive: httpConnection.setRequestProperty("Connection", "close");
  Post数据类型:httpConnection.setRequestProperty("Content-Type", mContentType);

posted @ 2012-09-06 17:43  TovenZhou  阅读(219)  评论(0编辑  收藏  举报