本章目的: 实现在Android客户端请求我们上篇建立的WCF数据服务.
此部分分为 建立Http请求 跟 接受WCF 返回的数据.
一. 建立Http请求的方法
protected String getRequest(String url, DefaultHttpClient client)
throws Exception {
String result = null;
int statusCode = 0;
HttpGet getMethod = new HttpGet(url);
Log.d(TAG, "do the getRequest,url=" + url + "");
try {
getMethod.setHeader("User-Agent", USER_AGENT);
// HttpParams params = new HttpParams();
// 添加用户密码验证信息
// client.getCredentialsProvider().setCredentials(
// new AuthScope(null, -1),
// new UsernamePasswordCredentials(mUsername, mPassword));
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());
throw new Exception(e);
} finally {
getMethod.abort();
}
return result;
}
参数URL: 我们要请求的地址
Client: 这个可以直接用new DefaultHttpClient(new BasicHttpParams()) 来初始化.
这个方法中需要注意RetrieveInputStream方法, 这个是当Http请求完成之后, 用来处理服务器返回数据的方法,
二. 接受从WCF端传回的数据
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 (UnsupportedEncodingException e) {
Log.e(TAG, e.getMessage());
} catch (IllegalStateException e) {
Log.e(TAG, e.getMessage());
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
return stringBuffer.toString();
}
此方法在接受到WCF服务端返回的数据之后, 转换程String类型返回.
附加内容:
private static final String BASE_URL = "http://10.0.2.2:82/BlogCategoryService/";
private static final String EXTENSION = "Json/";;
private static final String TAG = "API";
private static final String USER_AGENT = "Mozilla/4.5";
public JSONObject getObject(String sbj) throws JSONException, Exception {
return new JSONObject(getRequest(BASE_URL + EXTENSION + sbj));
}
public JSONArray getArray(String sbj) throws JSONException,
Exception {
return new JSONArray(getRequest(BASE_URL + EXTENSION + sbj));
}
protected String getRequest(String url) throws Exception {
return getRequest(url, new DefaultHttpClient(new BasicHttpParams()));
}
请求数据之前封装方法:
总结 : 此篇主要说明了Http请求的的两个阶段, 建立请求跟接受服务器返回的数据, 在下篇再主要说明如何处理服务端返回的JSON数据,并把数据显示在UI上面.