日期:2014-05-16  浏览次数:20297 次

通过json获取后台服务器数据
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class NetworkConnect {
      //服务器URL
private String base_url = "http://10.1.1.1:8080/Service/";
	private static final String TAG = "API";

        //返回得到object对象
	public JSONObject getJSONObject(String function,
			List<NameValuePair> nameValuePairs) {
		JSONObject json = null;
		String resultStr = getRequest(base_url + function, nameValuePairs);
		if (resultStr == "" || resultStr == null) {
			return null;
		}
		try {
			json = new JSONObject(resultStr);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return json;
	}

	protected String getRequest(String url, List<NameValuePair> nameValuePairs) {
		String result = "";
		int statusCode = 0;
		BasicHttpParams httpParams = new BasicHttpParams(); 
		HttpConnectionParams.setConnectionTimeout(httpParams, 3000); 
		HttpConnectionParams.setSoTimeout(httpParams, 3000);
		HttpClient client = new DefaultHttpClient(httpParams);
		HttpPost getMethod = new HttpPost(url);
		try {
			getMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		Log.d(TAG, "do the getRequest,url=" + url + "");
		try {
			HttpResponse httpResponse = client.execute(getMethod);
			// statusCode == 200 正常
			statusCode = httpResponse.getStatusLine().getStatusCode();
			Log.d(TAG, "statuscode = " + statusCode);
			// 处理返回的httpResponse信息
			result = retrieveInputStream(httpResponse.getEntity());
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
		} finally {
			getMethod.abort();
		}
		return result;
	}

	protected String retrieveInputStream(HttpEntity httpEntity) {
		int length = (int) httpEntity.getContentLength();
		if (length < 0)
			length = 10000;
		StringBuffer stringBuffer = new StringBuffer(length);
		try {
			InputStreamReader inputStreamReader = new InputStreamReader(
					httpEntity.getContent(), HTTP.UTF_8);
			char buffer[] = new char[length];
			int count;
			while ((count = inputStreamReader.read(buffer, 0, length - 1)) > 0) {
				stringBuffer.append(buffer, 0, count);
			}
		} catch (Exception e) {
		}
		return stringBuffer.toString();
	}
}
1 楼 ycl1229ycl 2011-12-14