我正在向我的数据库发送信息,但我不知道如何阅读我从JSON获得的响应,只需要阅读新活动中的“id”。你能给我发一个教程,或类似的东西。 这是我的数据验证。我的id为0,Id是一个字符串。
//数据验证在这里
if (isValid) {
// POST request to <service>/SaveGUID
HttpPost request = new HttpPost(url);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
// Build JSON string
JSONStringer via = new JSONStringer().object()
.key("id").value(checkId).key("username")
.value(usern).key("password").value(pass)
.endObject();
Log.i("JSON Object", via.toString());
StringEntity entity = new StringEntity(
via.toString());
Log.i("String Entity", entity.toString());
request.setEntity(entity);
// Send request to WCF service
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
Log.d("WebInvoke", "Saving : "
+ response.getStatusLine().getStatusCode());
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("id", checkId);
editor.commit();
next();
}
提前Tnx。
答案 0 :(得分:2)
从HttpResponse
获取JSON字符串:
// YOUR CODE HERE ....
StringEntity entity = new StringEntity(via.toString(),"UTF-8");
Log.i("String Entity", entity.toString());
request.setEntity(entity);
// Send request to WCF service
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
int statusCode = httpResponse.getStatusLine().getStatusCode();
Log.d("WebInvoke", "Saving : " + statusCode);
if (statusCode == 200) {
result = retrieveInputStream(httpResponse.getEntity());
Log.d("result result :: ",result);
}
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("id", checkId);
editor.commit();
next();
}
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();
}