奔跑的肥猪

导航

android如何在网络中获取数据

android获取数据无非通过get/post请求建立连接,后拿到response,根据解析。

具体实现如下:

1.

private void getXmlFromServer() {
		try {
			HttpHeadUtil util = new HttpHeadUtil(context);
			HttpResponse response = (requestBody == null || "".equals(requestBody)) ? util.getHttpResponse(action, param) : util.postHttpResponse(action, param, requestBody);
			if (response != null) {
				ResponseParse responseParse = new ResponseParse();
				responseParse.ResponseParse(response);
				resultCode = responseParse.getResultCode();
				xmlBody = responseParse.getResponseBody();
				timeStamp = responseParse.getTimeStamp();
			} else {
				this.resultCode = Constant.net_error_code;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

2.建立get连接

public HttpResponse get(String hostURL, final String requestBody, Map headers) {
		HttpResponse response = null;
		String actionName = headers.get("Action").toString();
		if (actionName == null || actionName.equals("")) {
			return response;
		}
		HttpGet get = null;
		try {
			HttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, Shdebug.TIMEOUT);
			HttpConnectionParams.setSoTimeout(httpParams, Shdebug.TIMEOUT);
			HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8);

			httpclient = new AMHttpClient(context, httpParams);
			if (Constant.IS_CMWAP_APN) {
				httpclient.getCredentialsProvider().setCredentials(new AuthScope(Constant.proxyUrl, Constant.proxyPort), new UsernamePasswordCredentials("cmwap", "cmwap"));
				HttpHost proxy = new HttpHost(Constant.proxyUrl, Constant.proxyPort);
				httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
			}
			get = new HttpGet(hostURL);
			Set ibaset = headers.keySet();
			Object[] obj = ibaset.toArray();
			for (int j = 0; j < obj.length; j++) {
				String ibaName = (String) obj[j];
				String ibaValue = (String) headers.get(ibaName);
				get.setHeader(ibaName, ibaValue);
				Log.v("===========HttpHeadUtil==========", "==========name: " + ibaName + " value: " + ibaValue);
			}
			Log.v("===========HttpHeadUtil==========", "==========host url: " + hostURL);
			response = httpclient.execute(get);

			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				get.abort();
			}
		} catch (Exception e) {
			e.printStackTrace();
			if (get != null)
				get.abort();

		}
		return response;
	}

3.解析response

private void parse(HttpResponse response) {
		if (response == null) {
			this.resultCode = Constant.net_error_code;
			return;
		}

		if (response != null) {
			// TimeStamp and ResultCode Mustn't null
			timeStamp = response.getFirstHeader("TimeStamp").getValue();
			resultCode = response.getFirstHeader("result-code").getValue();
			Header[] responseContentTypeHeaders = response.getHeaders("Content-Type");
			if (responseContentTypeHeaders != null && responseContentTypeHeaders.length == 1) {
				String type = responseContentTypeHeaders[0].toString();
			}

			Header[] responseTimeStampHeaders = response.getHeaders("TimeStamp");
			if (responseTimeStampHeaders != null && responseTimeStampHeaders.length == 1) {
				String timeStamp = responseTimeStampHeaders[0].toString();
				mTimeStamp = timeStamp.substring(timeStamp.indexOf(":") + 1, timeStamp.length()).trim();
				UtilTools.syncServerTime(mTimeStamp);

			}

			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				// 1.check content encoding type
				Header encodeHead = response.getFirstHeader("Content-Encoding");
				if (encodeHead != null) {
					contentEncoding = encodeHead.getValue().trim();
				}
				// 2.get http response content
				ByteArrayBuffer byteBuffer = new ByteArrayBuffer(BYTELENGTH);
				BufferedInputStream bis = null;
				InputStream is = null;
				byte[] contentByte;
				int byteReturnSize = 0;
				try {
					BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(response.getEntity());
					is = bufHttpEntity.getContent();
					bufHttpEntity.consumeContent();// confirm could read the all content
					// 3.use corresponding encode type to parse the content
					if (contentEncoding != null && contentEncoding.equals("gzip")) {
						GZIPInputStream gin = new GZIPInputStream(is);
						bis = new BufferedInputStream(gin);
					} else {
						bis = new BufferedInputStream(is);
					}
					contentByte = new byte[BYTELENGTH];
					while ((byteReturnSize = bis.read(contentByte, 0, contentByte.length)) >= 0) {
						byteBuffer.append(contentByte, 0, byteReturnSize);
					}
					xmlBody = new String(byteBuffer.toByteArray());
				} catch (Exception e) {
					e.printStackTrace();
				}
				finally {
					try {
						if (bis != null)
							bis.close();
						if (is != null)
							is.close();
					} catch (Exception e2) {
						e2.printStackTrace();
					}
				}
			}
		}
	}

其实在模拟器上能连接server,有工具可以拿到包的信息,名字叫Wireshark

挺好用的。

A:首先start wireshart,点击菜单中的capture start,该程序就开始监控网卡所有输入输出

B: 之后网卡所有的输入输出都在显示出来,选中某条记录,按ctrl+f,有一个输入框,选中string,如输入某个关键字,

点击find就能找到这个包。

C:找到该记录后,点击右键,选中follow tcp steam

d:弹出的框中选择save as可以将包的内容存储下来。

posted on 2011-07-13 17:06  布兜兜  阅读(1159)  评论(0编辑  收藏  举报