嗨,我在每个活动中都有这个 post 方法。我怎样才能把这篇文章放到一个类中,这样如果有错误我会知道?否则,我会将错误消息解析为 json。
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());
}