嗨我有這個帖子的方法在每一個活動。我怎麼能把這個帖子放到一個類中,如果錯誤我會知道?否則,我會將該錯誤消息解析爲json。Android post方法在一個類
private boolean login(String username, String password) {
TextView err = (TextView) findViewById(R.id.err);
boolean status = false;
String postData = "{\"Password\":\"" + password + "\",\"UserName\":\"" + username + "\"}";
try {
String domain = getString(R.string.domain);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
HttpPost httppost = new HttpPost(domain + "login");
StringEntity se = new StringEntity(postData.toString(), "utf-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
response = httpclient.execute(httppost);
if (response != null) {
HttpEntity r_entity = response.getEntity();
String json = EntityUtils.toString(r_entity);
JSONObject jsonobj = new JSONObject(json);
status = jsonobj.getBoolean("result");
}
} catch (Exception e) {
err.setText(e.getLocalizedMessage());
}
我不知道你在問什麼 - 無論是把它放在一個超級類,或創建一個實用程序類具有該方法? – 2012-04-25 19:16:52