【问题标题】:How to get the JSON error response and toast it?如何获取 JSON 错误响应并为其敬酒?
【发布时间】:2018-05-20 04:47:39
【问题描述】:

这是我尝试注册用户并需要 toast 时的代码,这是来自服务器的关于用户已经存在的响应。我可以使用 json 成功发布到服务器,但是如果有响应,我必须知道如何捕获它,图像显示了使用邮递员时的示例。

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{

private EditText signupInputName, signupInputEmail, signupInputPassword, retypeInputPassword;
private Button btnSignUp;
private Button btnLinkLogin;
private String message = "";
private int code = 0;

Person person;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    signupInputName = (EditText) findViewById(R.id.signup_input_name);
    signupInputEmail = (EditText) findViewById(R.id.signup_input_email);
    signupInputPassword = (EditText) findViewById(R.id.signup_input_password);
    retypeInputPassword = (EditText) findViewById(R.id.signup_retype_password);

    btnSignUp = (Button) findViewById(R.id.btn_signup);
    btnLinkLogin = (Button) findViewById(R.id.btn_link_login);

    btnSignUp.setOnClickListener(this);

    btnLinkLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent i = new Intent(getApplicationContext(),LoginActivity.class);
            startActivity(i);
        }
    });
}

public String POST(String url, Person person)
{
    InputStream inputStream = null;
    String result = "";

    try {

        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // 2. make POST request to the given URL
        HttpPost httppost = new HttpPost(url);

        String json = "";

        // 3. build jsonObject
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("user_name", person.getUsername());
        jsonObject.accumulate("email", person.getEmail());
        jsonObject.accumulate("password", person.getPassword());

        // 4. convert JSONObject to JSON to String
        json = jsonObject.toString();

        // ** Alternative way to convert Person object to JSON string usin Jackson Lib
        // ObjectMapper mapper = new ObjectMapper();
        // json = mapper.writeValueAsString(person);

        // 5. set json to StringEntity
        StringEntity se = new StringEntity(json);

        // 6. set httpPost Entity
        httppost.setEntity(se);

        // 7. Set some headers to inform server about the type of the content
        httppost.setHeader("Accept", "application/json");
        httppost.setHeader("Content-type", "application/json");

        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httppost);

        // 9. receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();

        // 10. convert inputstream to string
        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Error! email exist";

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    // 11. return result
    return result;
}

@Override
public void onClick(View view) {
    if(validate() == 1)
    {
        Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show();
    }
    else if (validate() == 2)
    {
        Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show();
    }
    else if (validate() == 3)
    {
        Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show();
    }
    else if (validate() == 4)
    {
        //Toast.makeText(getBaseContext(), "Success", Toast.LENGTH_SHORT).show();
        new HttpAsyncTask().execute("http://ip-addressses/api/register");
    }

}

private class HttpAsyncTask extends AsyncTask<String, Void, String>
{
    @Override
    protected String doInBackground(String... urls) {

        person = new Person();
        person.setUsername(signupInputName.getText().toString());
        person.setEmail(signupInputEmail.getText().toString());
        person.setPassword(signupInputPassword.getText().toString());

        return POST(urls[0],person);
    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {

        JSONObject jObject;

        try {
            jObject = new JSONObject(result);
            if (jObject.has("error")) {
                String aJsonString = jObject.getString("error");
                Toast.makeText(getBaseContext(), aJsonString, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getBaseContext(), "Login Successful", Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }


    }
}

private int validate() {
    if(signupInputName.getText().toString().trim().equals("") || signupInputEmail.getText().toString().trim().equals("") || signupInputPassword.getText().toString().trim().equals("") || retypeInputPassword.getText().toString().trim().equals(""))
    {
        code = 1;
        message = "Complete the form!";
    }
    else if (!(signupInputPassword.getText().toString().equals(retypeInputPassword.getText().toString())))
    {
        code = 2;
        message = "Re-check password";
    }
    else if (!isValidEmail(signupInputEmail.getText().toString()) ) {
        code = 3;
        message = "Invalid email";
    }
    else
        code = 4;

    return code;
}

public final static boolean isValidEmail(String target)
{
    if (target == null) {
        return false;
    } else {
        Matcher match = Patterns.EMAIL_ADDRESS.matcher(target);
        return match.matches();
    }
}

private static String convertInputStreamToString(InputStream inputStream) throws IOException{
    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;

}
}

存在电子邮件时的邮递员响应

【问题讨论】:

    标签: java android json


    【解决方案1】:

    只需更改此代码:

      jObject = new JSONObject(result);
      if (jObject.has("error")) 
      { 
          String aJsonString = jObject.getString("error");
          Toast.makeText(getBaseContext(), aJsonString, Toast.LENGTH_SHORT).show(); 
      }
      else 
      { 
          Toast.makeText(getBaseContext(), "Login Successful", Toast.LENGTH_SHORT).show(); 
      }
      }
      catch (JSONException e1) { 
          // TODO Auto-generated catch block 
          e1.printStackTrace(); 
          Toast.makeText(getBaseContext(),result+"" , Toast.LENGTH_SHORT).show();
       }
    

    因此,通过这段代码,如果您的响应不是 JSON,它将在 catch 中引发异常。在这里你可以显示吐司。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-16
      • 2016-11-29
      • 1970-01-01
      • 2017-06-21
      • 1970-01-01
      • 2019-01-18
      • 2019-01-22
      • 1970-01-01
      相关资源
      最近更新 更多