使用httpulrconnection

时间:2017-07-08 15:02:31

标签: android json login httpurlconnection

我已经设置了服务器以接受电子邮件&密码凭据,我希望我的应用程序使用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 :(得分:0)

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

另外,我已经在http://81.169.151.83/users/sign_in检查了您的网站,登录表单中使用的参数是用户[email]和用户[密码]。不是您在上面添加的电子邮件和密码。还有其他几个表单字段,例如authenticity_token,这可能是原因。