你如何实现Android 4.0 Restful,HTTP post请求

时间:2012-07-12 02:59:20

标签: android http http-post android-4.0-ice-cream-sandwich

由于他们改变了我们在最新Android SDK中发出HTTP请求的方式,因此我无法找到一个教程来说明如何发布HTTP post请求。特别是登录。所以我想看一些代码示例,展示如何实现HTTP post请求,并处理cookie。如果可能的话,我还希望看到https://security.stackexchange.com/questions/4302/how-to-implement-a-remember-me-on-a-mobile-app的代码示例。谢谢。

1 个答案:

答案 0 :(得分:2)

使用的图书馆:http://loopj.com/android-async-http/

private OnClickListener login = new OnClickListener() {

    public void onClick(View view) {

        AsyncHttpClient myClient = new AsyncHttpClient();
        myClient.get(URL, null);
        myClient.setCookieStore(myCookieStore);
        myClient.setCookieStore(myCookieStore);
        String username = "";
        String password = "";
        RequestParams params1 = new RequestParams();
        params1.put("username", username);
        params1.put("password", password);
        pd = ProgressDialog.show(this, "", "Signing In...");
        myClient.post(URL, params1,
                new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(String response) {
                        System.out.println("response" + response);
                        pd.dismiss();
                        if (response.contains("<!--Authorized-->")) {
                        }
                        else {
                            pd.dismiss();
                            Context mContext = SigninActivity.this;
                            notMatchDialog = new Dialog(mContext);
                            notMatchDialog.setContentView(R.layout.loginfaileddialoglayout);
                            notMatchDialog.setTitle("Login failed");
                            dismissDialogButton = (Button) notMatchDialog.findViewById(R.id.dismissDialogButton);
                            dismissDialogButton.setOnClickListener(dismissDialog);
                            notMatchDialog.show();
                        }
                    }

                    @Override
                    public void onFailure(Throwable e, String response) {
                        // TODO Need to figure out different failures and try to help the user.
                    }
                });
    }
};