Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/399.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/179.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Android中的HTML请求_Java_Android_Login_Android Asynctask_Httprequest - Fatal编程技术网

Java Android中的HTML请求

Java Android中的HTML请求,java,android,login,android-asynctask,httprequest,Java,Android,Login,Android Asynctask,Httprequest,这就是我的问题:我正在开发一个需要登录的移动应用程序。我在Android Studio/Java中编程。我在Java方面有很好的经验,但我从未做过网络。。服务器上有一个处理登录的.asp脚本,我需要将登录数据发送到该脚本。我认为解决这个问题的最好方法是HTTP请求,因为如果您在浏览器中输入脚本的url,然后输入包含登录数据的查询字符串,您已经得到了响应 http://sampleurl.info/actions/checklogin.asp?userName=klingenhaeger&

这就是我的问题:我正在开发一个需要登录的移动应用程序。我在Android Studio/Java中编程。我在Java方面有很好的经验,但我从未做过网络。。服务器上有一个处理登录的.asp脚本,我需要将登录数据发送到该脚本。我认为解决这个问题的最好方法是HTTP请求,因为如果您在浏览器中输入脚本的url,然后输入包含登录数据的查询字符串,您已经得到了响应

http://sampleurl.info/actions/checklogin.asp?userName=klingenhaeger&password=droid&device=android
返回包含配置文件令牌、时间戳和配置文件名称的Json字符串。如:

{"profil_token":"qn2hJcRQixYjG7yyW956g1407921902","profil_name":"Marc Klingenhäger","timestamp":"1407921902"}
然后将此配置文件令牌附加到用户请求的每个url,这样用户就可以获得对所有网站的权限。 我读到,您可以对http GET请求执行相同的操作,但我和我的同事一直在做这件事 (这么简单的一件事)为了我们的九年,我们的代码没有正常工作。。。 我们尝试了大量的代码片段,这是我们最简单的尝试: 在主活动中,单击导致登录的按钮时,将使用意图调用LoginActivity.class

        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
输入用户数据后,用户单击login按钮,方法attemptLogin();有人打电话来

public void attemptLogin() {
    if (mAuthTask != null) {
        return;
    }

    // Reset errors.
    mEmailView.setError(null);
    mPasswordView.setError(null);

    // Store values at the time of the login attempt.
    String email = mEmailView.getText().toString();
    String password = mPasswordView.getText().toString();

    boolean cancel = false;
    View focusView = null;


    // Check for a valid password, if the user entered one.
    if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
        mPasswordView.setError(getString(R.string.error_invalid_password));
        focusView = mPasswordView;
        cancel = true;
    }

    // Check for a valid email address.
    if (TextUtils.isEmpty(email)) {
        mEmailView.setError(getString(R.string.error_field_required));
        focusView = mEmailView;
        cancel = true;
    } else if (!isEmailValid(email)) {
        mEmailView.setError(getString(R.string.error_invalid_email));
        focusView = mEmailView;
        cancel = true;
    }

    if (cancel) {
        // There was an error; don't attempt login and focus the first
        // form field with an error.
        focusView.requestFocus();
    } else {
        // Show a progress spinner, and kick off a background task to
        // perform the user login attempt.
        showProgress(true);
        mAuthTask = new UserLoginTask(email, password);
        mAuthTask.execute((Void) null);
    }
}
因此,在一些错误检测之后,类userLoginTask(AsyncTask的子类)被初始化以处理网络内容,因为在主线程中初始化http请求似乎会导致异常。到目前为止,我们还没有在这里编写HTTP请求的代码。。(这是主要问题)

公共类UserLoginTask扩展异步任务{

    private final String mEmail;
    private final String mPassword;

    UserLoginTask(String email, String password) {
        mEmail = email;
        mPassword = password;
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        // TODO: attempt authentication against a network service.

        try {
            // Simulate network access.
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            return false;
        }

        for (String credential : DUMMY_CREDENTIALS) {
            String[] pieces = credential.split(":");
            if (pieces[0].equals(mEmail)) {
                // Account exists, return true if the password matches.
                return pieces[1].equals(mPassword);
            }
        }

        // TODO: register the new account here.
        return true;
    }

    @Override
    protected void onPostExecute(final Boolean success) {
        mAuthTask = null;
        showProgress(false);

        if (success) {
            finish();
        } else {
            mPasswordView.setError(getString(R.string.error_incorrect_password));
            mPasswordView.requestFocus();
        }
    }

    @Override
    protected void onCancelled() {
        mAuthTask = null;
        showProgress(false);
    }
}
所以我的问题基本上是,如何在UserLoginTask类中初始化HTTP请求。有什么想法吗?提前谢谢!)


Falco

最简单的方法是使用URL对象并打开到HTTP服务器的流。
可以通过以下流读取服务器响应:

String url = "http://sampleurl.info/actions/checklogin.asp?userName=klingenhaeger&password=droid&device=android";
try {
    URL u = new URL(url);
    InputStream is = u.openStream(); // Opens streaming connection to url
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));

    StringBuffer result = new StringBuffer(); // Buffer to store saved data
    String input = null;

    while((input = reader.readLine()) != null) {
        // Read data until the end of the stream
        result.append(input);
    }

    // Do something with result here
} catch (IOException e) {
    e.printStackTrace();
}
当您以字符串的形式检索数据时,您可以解析JSON以获取
配置文件\u令牌

使用Android的截取并发出HTTP POST请求,发送用户名/密码。 我建议对密码进行散列(MD5或其他东西-取决于后端处理的解密内容)。

谷歌建议使用

一个应该做您想做的事情的示例非常简单,特别是在使用GET时。首先,从字符串构造一个URL。您的响应是InputStream,您将其解析为JSONObject并获取您的令牌

URL url = new URL("http://sampleurl.info/actions/checklogin.asp?userName=klingenhaeger&password=droid&device=android");
//later:
URL url = new URL("http://sampleurl.info/actions/checklogin.asp?token=abcde");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
    readStream(in);
finally {
    urlConnection.disconnect();
}
}  

这是推荐的方法,因为它不需要任何外部库,并且可以很容易地转换为使用POST而不是GET,使用HTTPS而不是HTTP。

Cool,所以我通过编写一个方法getJsonString()来尝试它们这会执行你的代码。在调用这个方法时,虽然我得到了一个Exeption,因为网络是在主线程中执行的。我不能调用我在UserLoginTask中编写的方法,这是一个单独的线程。有人知道如何解决这个问题吗?嗯,你必须将代码放在doInBackground方法中。然后你可以让onPostExecute执行一次作为参数,它是下载的JSON字符串(从doInBackground返回):)