您的位置:首页 > 理论基础 > 计算机网络

从网络获取JSON格式数据

2012-11-20 10:19 288 查看
public JSONObject getJson() {
		JSONObject resultJson = null;
		if ("".equals(this.mUrl) || this.mUrl == null) {
			return null;
		}

		HttpClient httpClient = this.getHttpClient();
		StringBuilder uriStringBuilder = new StringBuilder(this.mUrl);
		StringBuilder resultStringBuilder = new StringBuilder();
		HttpGet httpGet = new HttpGet(uriStringBuilder.toString());
		BufferedReader bufferReader = null;
		HttpResponse httpResponse = null;
		try {
			httpResponse = httpClient.execute(httpGet);
		} catch (Exception e) {
			return null;
		}

		int status = httpResponse.getStatusLine().getStatusCode();
		if (HttpStatus.SC_OK == status) {
			HttpEntity entity = httpResponse.getEntity();
			if (entity != null) {
				try {
					bufferReader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"), 8192);
					String line = null;
					while ((line = bufferReader.readLine()) != null) {
						resultStringBuilder.append(line + "/n");
					}
					resultJson = new JSONObject(resultStringBuilder.toString());
				} catch (Exception e) {
					System.out.println("fail fail fail");		
				} finally {
					try {
						bufferReader.close();
					} catch (IOException e) {
						System.out.println("fail fail fail");
						e.printStackTrace();
					}
				}
			}

		} else {
			return null;
		}
		return resultJson;
	}
    
	public HttpClient getHttpClient() {
		this.mHttpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(this.mHttpParams, 20 * 1000);
		HttpConnectionParams.setSoTimeout(this.mHttpParams, 20 * 1000);
		HttpConnectionParams.setSocketBufferSize(this.mHttpParams, 8192);
		HttpClientParams.setRedirecting(this.mHttpParams, true);
		HttpClient client = new DefaultHttpClient(this.mHttpParams);
		return client;
	}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: