我已将服务器设置为接受电子邮件和密码凭据,并且我希望我的应用使用HttpURLconnection登录。 连接部分似乎还可以,因为响应始终为200,但实际上在发送数据时遇到了麻烦。 我将json对转换为字符串并通过DataOutputStream发送。 我通过InputStream读取了响应。

我的主要问题是,即使电子邮件和密码错误,我使用InputStream读取的响应也始终是相同的(登录页面的html),这使我认为我没有正确发送数据。

您可以看一下我的代码:

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.JsonWriter;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.app.ProgressDialog;
import java.io.DataOutputStream;
import java.net.MalformedURLException;
import android.net.Uri;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.content.Intent;
import org.json.JSONObject;
import org.json.JSONStringer;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

private EditText user;
private EditText pswrd;
private Button login;
private String email;
private String password;
private String HOST;
private String DEFAULT_IPADDRESS;
private String PREFERENCES_IPADDRESSSERVER;
private String PREFERENCES_TOKEN;
private Context ctx;
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private String sRequest;

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


    user = (EditText) findViewById(R.id.Email);
    pswrd = (EditText) findViewById(R.id.Password);
    login = (Button) findViewById(R.id.button);



    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            email = user.getText().toString();
            password = pswrd.getText().toString();
            try {
                //HttpURLConnection example = serverLogin(email, password);
                new AsyncLogin().execute(email, password);
            } catch (Exception e) {
                e.printStackTrace();
            }


        }
    });


}

private class AsyncLogin extends AsyncTask<String, String, String> {
    ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
    HttpURLConnection conn;
    URL url = null;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tLoading...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

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

            // Enter URL address
            url = new URL("http://81.169.151.83/users/sign_in");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "exception";
        }
        try {
            // Setup HttpURLConnection class to send and receive data
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestMethod("POST");

            // setDoInput and setDoOutput method depict handling of both send and receive
            conn.setDoInput(true);
            conn.setDoOutput(true);

            JSONObject request = new JSONObject();
            try {
                request.put("email", params[0]);
                request.put("password", params[1]);

            } catch (org.json.JSONException e) {
                e.printStackTrace();
            }
            sRequest = request.toString();




            // Open connection for sending data
            conn.connect();
            DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
            wr.writeBytes(sRequest);
            wr.flush();
            wr.close();


        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return "exception";
        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {


              // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // Pass data to onPostExecute method
                return (result.toString());

            } else {

                return ("unsuccessful");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return "exception";
        } finally {
            conn.disconnect();
        }


    }

    @Override
    protected void onPostExecute(String result) {

        //this method will be running on UI thread

        pdLoading.dismiss();

        if (result.equalsIgnoreCase("true")) {
            /* Here launching another activity when login successful. If you persist login state
            use sharedPreferences of Android. and logout button to clear sharedPreferences.
             */
            Toast.makeText(MainActivity.this, "GREAT SUCCESS", Toast.LENGTH_LONG).show();
         /*   Intent intent = new Intent(MainActivity.this,SuccessActivity.class);
            startActivity(intent);
            MainActivity.this.finish();*/

        } else if (result.equalsIgnoreCase("false")) {

            // If username and password does not match display a error message
            Toast.makeText(MainActivity.this, "Invalid email or password", Toast.LENGTH_LONG).show();

        } else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {

            Toast.makeText(MainActivity.this, "OOPs! Something went wrong. Connection Problem.", Toast.LENGTH_LONG).show();

        }
    }

}

谢谢

===============>>#1 票数:0

我建议您尝试OKHTTP ,查看他们的食谱 ,在Android中执行GET / POST请求要简单得多。

附带一提,我已经在http://81.169.151.83/users/sign_in上签出了您的网站,用于登录表单的参数是user [email]和user [password]。 不是您在上面添加的电子邮件和密码。 也可能是其他几个表单字段,例如authenticity_token。

  ask by Julio Arellano translate from so

未解决问题?本站智能推荐: