Android 开发过程网络相关问题

1.发送request.
a. post:
生成请求
HttpPost request = new HttpPost(url);
HttpClient httpClient = new DefaultHttpClient();

设置30s连接不上则失败
httpClient.getConnectionManager().closeIdleConnections(30,TimeUnit.SECONDS);

发送请求,获得返回结果
response = httpClient.execute(request);
HttpEntity httpEntity = response.getEntity();


基本代码如下:

public Entity httpPost(String url) {
		if (url == null || url.equals("")) {
			return null;
		}
		HttpPost request = new HttpPost(url);
		httpClient.getConnectionManager().closeIdleConnections(30,TimeUnit.SECONDS);

		HttpResponse response;
		Entity value = null;
        try {
	        response = httpClient.execute(request);
	        HttpEntity httpEntity = response.getEntity();
	        if (httpEntity != null) {
	        	value = new Entity(asString(httpEntity).toString());
	        	httpEntity.consumeContent();
	        }
        }
        catch (ClientProtocolException e1) {
	        e1.printStackTrace();
        }
        catch (IOException e1) {
	        e1.printStackTrace();
        }
		return value;
	}


用到包如下:
commons-codec-1.4.jar
commons-logging-1.1.1.jar
httpclient-4.0.1.jar
httpcore-4.0.1.jar
MapApi.jar
不可直接下载可以在
http://hc.apache.org/downloads.cgi下载

我们的网络连接用http.rar中方法
调用时new LBSHttpClient().httpPost(url.toString()).asJSONObject();就OK了
instancel 中有具体调用

2. 对JSON的解析:
因为用某些方法存在中文得到的是\uxxxx的unicode码,我们用了一个开源的类用来解析json.
相关类,会以压缩包的形式提交。

对json的具体解析方法是:
a. JSONObject.
jsonObject.getString();
jsonObject.getXXX();

b. JSONArray.

jsonArray = jsonObject.getJSONArray("circle_list");
            Log.d (TAG, "jsonArray.length():" + jsonArray.length());
            for (int i = 0; i < jsonArray.length() ; i ++){
                Log.d (TAG, "3");
                JSONObject circleObject = jsonArray.getJSONObject(i);
                CircleInfo circleInfo = new CircleInfo();
                circleInfo.setTag(circleObject.getString("tag"));
                circleInfo.setName(circleObject.getString("name"));
                circleInfo.setMemNum(circleObject.getLong("memner_num"));
                circleInfo.setCityName(circleObject.getString("city_name"));
                circleInfo.setId(circleObject.getLong("id"));
                circleInfo.setImageId(circleObject.getLong("image_id"));
                list.add(circleInfo);
            }

你可能感兴趣的:(java,apache,json,android,cgi)