如何获取JSON错误响应并烘烤它?

时间:2017-12-06 10:26:45

标签: java android json

这是我的代码,当我尝试注册用户并需要一个吐司,这是来自服务器的关于用户的响应已经存在。我可以使用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;

}
}

电子邮件存在时的邮递员回复

image

1 个答案:

答案 0 :(得分: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中抛出异常。在这里你可以举杯祝酒。