Android Studio连接到URL

My problem is that I made a "web" with php to register, login and logout. What I really want to do is connect the web to my app in android studio, it worked before I put the page welcome in the website, but when I try to apply the changes, the app fails when I login.

The website:

http://saveds.esy.es/cas/login.php

The Android Studio code in java by directories:

JSONParser.java

package com.example.javi.myapplication2;

import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}


public JSONObject getJSONFromUrl(final String url) {

    // Making HTTP request
    try {
        // Construct the client and the HTTP request.
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        // Execute the POST request and store the response locally.
        HttpResponse httpResponse = httpClient.execute(httpPost);
        // Extract data from the response.
        HttpEntity httpEntity = httpResponse.getEntity();
        // Open an inputStream with the data content.
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        // Create a BufferedReader to parse through the inputStream.
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        // Declare a string builder to help with the parsing.
        StringBuilder sb = new StringBuilder();
        // Declare a string to store the JSON object data in string form.
        String line = null;

Login.java

package com.example.javi.myapplication2;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity implements OnClickListener {

private EditText user, pass;
private Button mSubmit, mRegister;
private CheckBox check;


private ProgressDialog pDialog;

// Clase JSONParser
JSONParser jsonParser = new JSONParser();


// si trabajan de manera local "localhost" :
// En windows tienen que ir, run CMD > ipconfig
// buscar su IP
// y poner de la siguiente manera
// "http://xxx.xxx.x.x:1234/cas/login.php";

private static final String LOGIN_URL = "http://saveds.esy.es/cas/login.php";

// La respuesta del JSON es
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);

    // setup input fields
    user = (EditText) findViewById(R.id.username);
    pass = (EditText) findViewById(R.id.password);
    check = (CheckBox) findViewById(R.id.rememberme);

    // setup buttons
    mSubmit = (Button) findViewById(R.id.login);
    mRegister = (Button) findViewById(R.id.register);

    // register listeners
    mSubmit.setOnClickListener(this);
    mRegister.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
        case R.id.login:
            new AttemptLogin().execute();
            break;
        case R.id.register:
            Intent i = new Intent(this, Register.class);
            startActivity(i);
            break;

        default:
            break;
    }
}

class AttemptLogin extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Login.this);
        pDialog.setMessage("Attempting login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {
        int success;
        String username = user.getText().toString();
        String password = pass.getText().toString();
        String rememberme = check.getText().toString();

        try {
            // Building Parameters
            List params = new ArrayList();
            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("password", password));
            params.add(new BasicNameValuePair("rememberme", rememberme));


            Log.d("request!", "starting");
            // getting product details by making HTTP request
            JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
                    params);

            // check your log for json response
            Log.d("Login attempt", json.toString());

            // json success tag
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("Login Successful!", json.toString());
                // save user data
                SharedPreferences sp = PreferenceManager
                        .getDefaultSharedPreferences(Login.this);
                Editor edit = sp.edit();
                edit.putString("username", username);
                edit.commit();

                Intent i = new Intent(Login.this, ReadComments.class);
                finish();
                startActivity(i);
                return json.getString(TAG_MESSAGE);
            } else {
                Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                return json.getString(TAG_MESSAGE);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;

    }

    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();
        if (file_url != null) {
            Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
        }
    }
}
}

ReadComments.java

package com.example.javi.myapplication2;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class ReadComments extends Activity implements OnClickListener{

private Button logout;

// Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();

//si lo trabajan de manera local en xxx.xxx.x.x va su ip local
// private static final String REGISTER_URL = "http://xxx.xxx.x.x:1234/cas/register.php";

//testing on Emulator:
private static final String WELCOME_URL = "http://saveds.esy.es/cas/welcome.php";

//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.read_comments);

    logout=(Button)findViewById(R.id.logout);
    logout.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

    new Logoutclass().execute();

}

class Logoutclass extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(ReadComments.this);
        pDialog.setMessage("Cerrando sesión...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
        // Check for success tag
        int success;
        String out=logout.getText().toString();

        try {
            // Building Parameters
            List params = new ArrayList();
            params.add(new BasicNameValuePair("username", out));

            Log.d("request!", "starting");

            //Posting user data to script
            JSONObject json = jsonParser.makeHttpRequest(
                    WELCOME_URL, "POST", params);

            // full json response
            Log.d("Cerrando sesión", json.toString());

            // json success element
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("Sesión cerrada", json.toString());
                finish();
                return json.getString(TAG_MESSAGE);
            }else{
                Log.d("Fallo de cerrar sesión", json.getString(TAG_MESSAGE));
                return json.getString(TAG_MESSAGE);

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

        return null;

    }

    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();
        if (file_url != null){
            Toast.makeText(ReadComments.this, file_url, Toast.LENGTH_LONG).show();
        }
    }
}
}

register.java

package com.example.javi.myapplication2;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Register extends Activity implements OnClickListener{
private EditText user, pass, nam, mail ;
private Button  mRegister;

// Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();

//si lo trabajan de manera local en xxx.xxx.x.x va su ip local
// private static final String REGISTER_URL = "http://xxx.xxx.x.x:1234/cas/register.php";

//testing on Emulator:
private static final String REGISTER_URL = "http://saveds.esy.es/cas/register.php";

//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.register);

    user = (EditText)findViewById(R.id.username);
    pass = (EditText)findViewById(R.id.password);
    nam = (EditText)findViewById(R.id.name);
    mail = (EditText)findViewById(R.id.email);


    mRegister = (Button)findViewById(R.id.register);
    mRegister.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

    new CreateUser().execute();

}

class CreateUser extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Register.this);
        pDialog.setMessage("Creating User...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
        // Check for success tag
        int success;
        String email=mail.getText().toString();
        String name = nam.getText().toString();
        String username = user.getText().toString();
        String password = pass.getText().toString();

        try {
            // Building Parameters
            List params = new ArrayList();
            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("password", password));
            params.add(new BasicNameValuePair("name", name));
            params.add(new BasicNameValuePair("email", email));

            Log.d("request!", "starting");

            //Posting user data to script
            JSONObject json = jsonParser.makeHttpRequest(
                    REGISTER_URL, "POST", params);

            // full json response
            Log.d("Registering attempt", json.toString());

            // json success element
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("User Created!", json.toString());
                finish();
                return json.getString(TAG_MESSAGE);
            }else{
                Log.d("Registering Failure!", json.getString(TAG_MESSAGE));
                return json.getString(TAG_MESSAGE);

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

        return null;

    }

    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();
        if (file_url != null){
            Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show();
        }
    }
}
}

Do I have to put the PHP code?

The error:

1

2

douxieti6851
douxieti6851 删除pDialog并再次调试,看看抛出了什么错误
4 年多之前 回复
dongyang448966
dongyang448966 我编辑了它,但是有错误
4 年多之前 回复
douju8782
douju8782 发布你的logcat
4 年多之前 回复
dtp87205
dtp87205 我会试试@AlokGupta
4 年多之前 回复
dongyi1215
dongyi1215 你可以在调试模式下在模拟器中试用它并发布你得到的错误消息吗?
4 年多之前 回复
douge3492
douge3492 当我尝试在手机中运行它时,我使用验证用户名登录该应用程序关闭@AlokGupta
4 年多之前 回复
douruanfan3030
douruanfan3030 我的意思是您尝试登录时收到的错误日志。
4 年多之前 回复
dpf5207
dpf5207 什么是错误跟踪?
4 年多之前 回复
duanliu6083
duanliu6083 你能发布完整的错误跟踪吗?
4 年多之前 回复

2个回答

Hey Pepe without seeing error whatever you got will make us complex to give you solution.

apart from that you can change your code like below

String data = URLEncoder.encode("user_email", "UTF-8")
            + "=" + URLEncoder.encode(user_email, "UTF-8");

       data += "&" + URLEncoder.encode("user_password", "UTF-8") + "="
            + URLEncoder.encode(user_password, "UTF-8");


    value = data;

        URL url;
        String response = "";
        try {
            url = new URL("Provide your URL here...");

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);


            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            //writer.write(getPostDataString(postDataParams));
            writer.write(value);

            writer.flush();
            writer.close();
            os.close();
            int responseCode = conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while ((line = br.readLine()) != null) {
                    response += line;
                    System.out.println(response);
                }
            } else {
                response = "";

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

Enjoy, Happy coding....

doqrjrc95405
doqrjrc95405 在您的JSONParser.java中
4 年多之前 回复
dslfq06464
dslfq06464 我把它放在哪里?,抱歉,我是这个@Laxmeena的新手
4 年多之前 回复
dongxun6458
dongxun6458 too long
4 年多之前 回复
doucheng1891
doucheng1891 不,我认为错误在这里受到保护String doInBackground(String ... args){int success; String username = user.getText()。toString(); String password = pass.getText()。toString(); String rememberme = check.getText()。toString(); try {List params = new ArrayList(); params.add(new BasicNameValuePair(“username”,username)); params.add(new BasicNameValuePair(“password”,password)); params.add(new BasicNameValuePair(“rememberme”,rememberme));
4 年多之前 回复
duanhemou9834
duanhemou9834 首先在Login.java中。 告诉我,登录成功与否。
4 年多之前 回复
dragonpeng200811111
dragonpeng200811111 在什么目录?
4 年多之前 回复
dongyu9263
dongyu9263 Plz调用Intent i = new Intent(Login.this,ReadComments.class); 完(); 在postExecute方法..
4 年多之前 回复
donglu5235
donglu5235 我编辑了@Laxmeena的帖子
4 年多之前 回复

When you get this error, it means your window is leaking the progress dialog.

Try this

class AttemptLogin extends AsyncTask<String, String, String> {
    ProgressDialog pDialog; // add your pDialog here
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Login.this, "Attempting to login",null);

    }

You should not add the Intent in doInBackground, instead put them in onPostExecute. Read this article for logIn and logOut example.

duan0417
duan0417 我把它放在哪里?
4 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问