1

我已经看到了更多这样的问题,但没有设法理解它们,或者它们不适用于我的问题,所以就这样吧。

我有一个 Activity 允许您登录,另一个您可以使用您的登录凭据发送 POST 和 GET 请求等。

主要活动:

public class MainActivity extends Activity
{

    private String username;
    private String password;

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

        final EditText usernameField = (EditText) findViewById(R.id.enterUsername);

        final EditText passwordField = (EditText) findViewById(R.id.enterPassword);

        Button startButton = (Button) findViewById(R.id.startButton);
        startButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View view)
            {
                username = usernameField.getText().toString();
                password = passwordField.getText().toString();
                Intent myIntent = new Intent(view.getContext(), HttpGetPost.class);
                startActivityForResult(myIntent, 0);
            }
        });
    }

    public String getUser() { return this.username; }
    public String getPassword() { return this.password; }
}

HttpGetPost:

public class HttpGetPost extends Activity
{

    private MainActivity mainProxy = new MainActivity();
    private Button postButton;
    private Button getButton;
    private Button getMeasureButton;
    private Button getDevicesButton;
    private String access_token;
    private String refresh_token;
    private String device_list;
    private String expires_in;
    private String getRequest;
    private static final String TAG = "MyActivity";
    private static final String USER_AGENT = "Mozilla/5.0";
    private String clientID = some_id;
    private String clientSecret = some_secret;
    private String user = mainProxy.getUser();
    private String pass = mainProxy.getPassword();

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

        Log.v(TAG, "mainProxy.username: "+user);
        Log.v(TAG, "mainProxy.password: "+pass);

        postButton = (Button) findViewById(R.id.postButton);
        postButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                new sendPost().execute("");
            }
        });
    }

    private class sendPost extends AsyncTask<String, Void, String>
    {
        @Override
        protected String doInBackground(String... params)
        {
            try
            {
                String url = some_url;
                URL obj = new URL(url);
                HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

                //add request header
                con.setRequestMethod("POST");
                con.setRequestProperty("User-Agent", USER_AGENT);
                con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

                String urlParameters = "grant_type=password&client_id=" +clientID +"&client_secret="
                    +clientSecret +"&username=" +user +"&password=" +pass;

                // Send post request
                con.setDoOutput(true);
                DataOutputStream wr = new DataOutputStream(con.getOutputStream());
                wr.writeBytes(urlParameters);
                wr.flush();
                wr.close();

                int responseCode = con.getResponseCode();
                Log.v(TAG, "\nSending 'POST' request to URL : " + url);
                Log.v(TAG, "Post parameters : " + urlParameters);
                Log.v(TAG, "Response Code : " + responseCode);

                BufferedReader in = new BufferedReader(
                        new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                //print result
                Log.v(TAG, response.toString());

                if (responseCode == 200)
                {
                    access_token = response.substring(17, 74);
                    refresh_token = response.substring(93,150);
                    expires_in = response.substring(165, 170);
                    getRequest = "http://api.netatmo.net/api/getuser?access_token=" +access_token + " HTTP/1.1";

                    Log.v(TAG, "access token: " +access_token);
                    Log.v(TAG, "refresh token: " +refresh_token);
                    Log.v(TAG, "expires in: " +expires_in);
                }

            }
            catch(Exception e){
                e.printStackTrace();
            }

            return "";
        }
        protected void onPostExecute(String result) {
            Toast.makeText(getApplicationContext(), "ENDED", Toast.LENGTH_LONG).show();
        }
    }

}

当我在第二类中打印出用户名和密码时,它们都返回 null,并且 POST 请求失败。

4

5 回答 5

4

为了澄清我在 jbihan 回答的评论中的意思:

我正在更新您的代码:

第一次修订:

Button startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener()
{
    public void onClick(View view)
    {
        username = usernameField.getText().toString();
        password = passwordField.getText().toString();
        Intent myIntent = new Intent(view.getContext(), HttpGetPost.class);
        // ADDITION
        myIntent.putExtra("username", username);
        myIntent.putExtra("password", password);
        // END ADDITION
        startActivityForResult(myIntent, 0);
    }
});

第二次修订:

 postButton = (Button) findViewById(R.id.postButton);
 // ADDITION
 final String user = getIntent().getStringExtra("username");
 final String password = getIntent().getStringExtra("password");
 // END ADDITION
 postButton.setOnClickListener(new View.OnClickListener()
 {
     @Override
     public void onClick(View view)
     {
         // EDITED
         new sendPost().execute(user, password);
     }
 });

第三次修订:

private class sendPost extends AsyncTask<String, Void, String>
{
    @Override
    protected String doInBackground(String... params)
    {
         // ADDITION
         String user = params[0];
         String password = params[1];
         // END ADDITION             

         // use them in the request
         // rest of code...

    }
}

请考虑为“用户名”和“密码”键使用常量。

于 2013-08-27T16:05:56.490 回答
4

您应该使用意图的 putExtra 方法将用户名和密码传递给您的活动:

Intent myIntent = new Intent(view.getContext(), HttpGetPost.class);
myIntent.putExtra("username", username);
myIntent.putExtra("password", pasword);
startActivityForResult(myIntent, 0);

在您的第二个活动中,在 onCreate() 中(例如在 setContentView 之后),您可以使用 getXXExtras 检索它们:

Intent intent = getIntent();

String username = intent.getStringExtra("username");
String password = intent.getStringExtra("password");
于 2013-08-27T15:38:19.737 回答
1

尝试使用附加功能:

Intent myIntent = new Intent(view.getContext(), HttpGetPost.class);
myIntent.putExtra("username", username);
myIntent.putExtra("password", password);
startActivityForResult(myIntent, 0);

在其他活动中(您的 HttpGetPost)

String user = getIntent().getStringExtra("username");
String password = getIntent().getStringExtra("password");
于 2013-08-27T15:42:31.317 回答
1

这是一个关于正确使用 Intent的很好的教程。

试试这个 HttpGetPost Activity 调用:

Intent myIntent = new Intent(this, HttpGetPost.class);
myIntent.putExtra("username", username);
myIntent.putExtra("password", password);
startActivity(myIntent);

随着this您在 Intent 构造函数中传递正确的上下文。将数据放入要发送到 Activity 的 Intent 中。下一点是不要调用 startActivityForResult(),它用于调用一个 Activity,进行一些计算并将结果发送回请求的 Activity。

现在像这样在 onCreate 中从 HttpGetPost Activity 中的 Intent 中获取数据并将其保存到一个字段中:

getIntent().getExtras().getString("username");
getIntent().getExtras().getString("password");
于 2013-08-27T15:44:55.887 回答
1

你不需要

private MainActivity mainProxy = new MainActivity();

在 HttpGetPost 中。它将创建一个新的 MainActivity,它不是启动 HttpGetPost 的原始活动。

您可以使用 extras 跨意图发送数据。这是我的解决方案:

把它放在 MainActivity

Intent myIntent = new Intent(view.getContext(), HttpGetPost.class);
myIntent.putExtra(HttpGetPost.KEY_USERNAME, username);
myIntent.putExtra(HttpGetPost.KEY_PASSWORD, password);
startActivityForResult(myIntent, 0);

这是针对 HttpGetPost 的,KEY_USERNAME 和 KEY_PASSWORD 可以用来存储额外的密钥,这样就可以避免拼写错误。

public static final String KEY_USERNAME = "username"; // or whatever you like for key
public static final String KEY_PASSWORD = "password"; // or whatever you like for key

private String user; // instead of private String user = mainProxy.getUser();
private String pass; // instead of private String pass = mainProxy.getPassword();

将其放在 HttpGetPost 的 onCreate 中以从意图中获取数据

Intent intent = getIntent();

user = intent.getStringExtra(KEY_USERNAME);
pass = intent.getStringExtra(KEY_PASSWORD);

是意图的官方文档。

于 2013-08-27T15:59:30.283 回答