我正在尝试发送带有信息电子邮件地址,名字和姓氏的JSON,并希望服务器回复说{status:“Created”}或{status:“Resend”}并根据答案而定将是一个弹出消息。我想知道我用什么来从状态类中提取信息。谢谢! 这是我接受的代码
protected void sendJson(final String email, final String firstN,
final String lastN) {
Thread t = new Thread() {
public void run() {
Looper.prepare(); // For Preparing Message Pool for the child
// Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(),
10000); // Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try {
// post in the url
HttpPost post = new HttpPost(
"https://iphone-radar.com/accounts");
json.put("email_address", email);
json.put("first_name", firstN);
json.put("last_name", lastN);
StringEntity se = new StringEntity("JSON: "
+ json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(se);
response = client.execute(post);
/* Checking response */
if (response != null) {
String str = response.getEntity().toString();
if (str.equals("Created")) {
new AlertDialog.Builder(CreateAccount.this)
.setTitle("Account Creation Successful")
.setMessage(
"An activation code has been sent to you. Please check your SPAM folder if you do not receive your activation code email")
.setNeutralButton("OK", null).show();
} else if(str.equals("Resend")) {
new AlertDialog.Builder(CreateAccount.this)
.setTitle("Code Resent")
.setMessage(
"Your activation code has been resent to your email.\n\nIf you are not receiving your activation code, our email is being blocked. Please email us at 'help@iphone-tracker.net' and we will manually send you a code.")
.setNeutralButton("OK", null).show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
答案 0 :(得分:2)
您应该将响应转换为字符串,然后创建JSONObject。然后,您可以只访问JSON对象的属性。试试这个:
org.json.JSONObject obj = new org.json.JSONObject(org.apache.http.util.EntityUtils.toString(response.getEntity()));
if ("Created".equals(obj.getString("status"))) {
new AlertDialog.Builder(CreateAccount.this)
.setTitle("Account Creation Successful")
.setMessage(
"An activation code has been sent to you. Please check your SPAM folder if you do not receive your activation code email")
.setNeutralButton("OK", null).show();
} else if("Resend".equals(obj.getString("status"))) {
new AlertDialog.Builder(CreateAccount.this)
.setTitle("Code Resent")
.setMessage(
"Your activation code has been resent to your email.\n\nIf you are not receiving your activation code, our email is being blocked. Please email us at 'help@iphone-tracker.net' and we will manually send you a code.")
.setNeutralButton("OK", null).show();
}