Android - 休息后呼叫

时间:2015-03-09 19:16:47

标签: android rest http post

我在给休息api打电话时遇到了一些麻烦。使用Chrome高级休息客户端时,我使用网址: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
}

3 个答案:

答案 0 :(得分:1)

对于追加请求参数,最终网址不应如下所示:

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

答案 1 :(得分:1)

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

调用url.openConnection()后,需要调用urlConnection.setRequestMethod(&#34; POST&#34;)。

正如Jayesh所提到的那样,您的网址也不正确。

答案 2 :(得分:0)

我通过重写类来使用JSON解析器修复了这个问题。