我正在开发一个简单的登录应用程序。我的 JSON Web 服务返回用户名。这是 JSON 代码的格式:
[{"demologin":{"username":"demoname","id":100}}]
这是我的代码:
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
username=txtUserName.getText().toString();
password=txtPassword.getText().toString();
String url="MY URL HERE";
HttpGet httpGet = new HttpGet(url);
String text = null;
String result = null;
String webusername=null;
int webuserid;
ArrayList<String> desc=new ArrayList<String>();
try {
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
JSONArray ja = new JSONArray(text) ;
// ITERATE THROUGH AND RETRIEVE CLUB FIELDS
int n = ja.length();
for (int i = 0; i < n; i++) {
// GET INDIVIDUAL JSON OBJECT FROM JSON ARRAY
JSONObject jo = ja.getJSONObject(i);
webusername= jo.getString("demologin");
webuserid= jo.getInt("id");
}
} catch (Exception e) {
e.getLocalizedMessage();
}
return webusername;
}
protected void onPostExecute(String results) {
if (results!=null) {
String sendusername=results;
Intent inte=new Intent(Login.this,FrontPage.class);
inte.putExtra("displayusername", sendusername);
startActivity(inte);
}
else
Toast.makeText(getApplicationContext(), "Invalid user", Toast.LENGTH_LONG).show();
}
}
这里的问题是我不知道如何将用户名转换为字符串并通过网络传递。有谁知道如何做到这一点?