Android 4.x中HttpURLConnection的getResponseCode返回值为空

来源(CSDN博客)

From: https://blog.csdn.net/leegh1992/article/details/45198591

Android 4.x中HttpURLConnection的getResponseCode返回值为空

原创 2015年04月22日 18:06:37 标签:android 1426

最近在做安卓毕业设计,我用的是安卓4.2.2,在从Android客户端读取服务器端上的json格式文件,并解析,遇到了这样一个问题,代码如下:

URL url = new URL("http://192.168.1.102:8080/VolunteerSystem/test.json");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
int code = 0;
code = conn.getResponseCode();


在Android2.x中,客户端发出请求,如果连接成功,就会有响应码code,如果code=200,说明服务器端成功响应。如果在Android4.x中,即使连接成功,响应码为空,不提示任何错误。

解决方法:由于网络请求是个耗时操作,不能放在主线程中执行,需要将将请求操作放在线程中。以下代码是读取json格式文件和解析json的具体代码,如下:

private Handler handler = new Handler() {
	public void handleMessage(android.os.Message msg) {
		switch (msg.what) {
			case LOAD_SUCCESS:
			if (mlists != null) {
				mListView.setAdapter(new FinanceAdapter());
			} else {
				Toast.makeText(getActivity(), "解析xml失败.", 1).show();
			}
			break;
			case LOAD_ERROR:
			Toast.makeText(getActivity(), "获取数据失败.", 1).show();
			break;
		}
	};
};



new Thread() {
	public void run() {
		try {
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[] data = new byte[1024];
			int len = 0;
			String path = Url.ipString + "/test.json";
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5000);
			int code = conn.getResponseCode();
			if (code == 200) {
				InputStream is = conn.getInputStream();
				while ((len = is.read(data)) != -1) {
					outStream.write(data, 0, len);

				}
				is.close();
				data = outStream.toByteArray();
				mlists = new ArrayList<Person>();
				JSONArray array = new JSONArray(new String(data));
				for (int i = 0; i < array.length(); i++) {
					JSONObject item = array.getJSONObject(i);
					String nickname = item.getString("nickname");
					String name = item.getString("name");
					String things = item.getString("things");
					mlists.add(new Person(nickname, name, things));
				}
				// TODO: 已经获取到数据 设置listview的里面要显示的内容了.
				Message msg = Message.obtain();
				msg.what = LOAD_SUCCESS;
				handler.sendMessage(msg);

			} else {
				// TODO:请求失败 通知ui更新.
				Message msg = Message.obtain();
				msg.what = LOAD_ERROR;
				handler.sendMessage(msg);
			}

		} catch (Exception e) {
			e.printStackTrace();
			// TODO:请求失败 通知ui更新.
			Message msg = Message.obtain();
			msg.what = LOAD_ERROR;
			handler.sendMessage(msg);
		}
	};
}.start();


至此,问题就得到了解决!

Link: http://www.asm32.net/article_details.aspx?id=7277


浏览次数 0 发布时间 2018/4/11 1:10:27 从属分类 Android 安卓 【评论】【 】【打印】【关闭
 
| www.asm32.net | 2006版 | 资料中心 | linux | asm/asm32 | C/C++ | VC++ | java | Python | 书签 | ASP.Net书签 | 京ICP备09029108号-1