Android - 休息 Post 呼叫

Android - Rest Post Call

我在调用 post 休息 api 时遇到了一些麻烦。使用 Chrome Advanced Rest Client 时,我使用 URL : http://example.com/task_manager/v1/register 进行测试,效果很好。我正在尝试让用户能够通过 android 进行注册。当我点击我的按钮时,我没有看到数据库有任何变化。

我正在通过 xml android:onClick="register"

调用方法
public class LoginActivity extends Activity {
    public EditText enterEmail;
    public EditText enterPassword;
    public EditText forgotPassword;
    public ImageButton loginButton;
    public ImageButton RegisterButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //hide status bar
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.login_activity);
        enterEmail = (EditText) findViewById(R.id.emailentry);
        enterPassword = (EditText) findViewById(R.id.passwordentry);
        forgotPassword = (EditText) findViewById(R.id.forgotpass);
        //login
        loginButton = (ImageButton) findViewById(R.id.loginbutton);

        //register
        RegisterButton = (ImageButton) findViewById(R.id.registerbutton);

    }

    public void login(View view){

    }

    public void register(View view){
        String email = enterEmail.getText().toString();
        String password = enterPassword.getText().toString();
        String name = "ANDROID";
        String apiURL = "http://example.com/task_manager/v1/register";

        if( (email != null && !email.isEmpty()) && (password != null && !password.isEmpty()) && (name != null && !name.isEmpty())) {

            String urlString = apiURL + "name="+name+"&email="+email+"&password="+password;

            new CallAPI().execute(urlString);

        }
    }



    private class CallAPI extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... params) {

            String urlString=params[0]; // URL to call

            String resultToDisplay = "";

            InputStream in = null;

            // HTTP Get
            try {

                URL url = new URL(urlString);

                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                in = new BufferedInputStream(urlConnection.getInputStream());

            } catch (Exception e ) {

                System.out.println(e.getMessage());

                return e.getMessage();

            }

            return resultToDisplay;
        }

        protected void onPostExecute(String result) {

        }

    } // end CallAPI
}

为了追加请求参数,结尾url不应该像下面这样:

String apiURL = "http://example.com/task_manager/v1/register?";

如果您的问题重点在于发出 POST 请求,您需要在调用 getInputStream 之前设置请求方法。

调用url.openConnection()后需要调用urlConnection.setRequestMethod("POST")。

正如 Jayesh 所说,您的 URL 似乎也不正确。

我通过重写 class 来使用 JSON 解析器解决了这个问题。