douyinmian8151 2016-02-22 06:48
浏览 304

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

  • 写回答

2条回答 默认 最新

  • duananyantan04633 2016-02-22 07:11
    关注

    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....

    评论

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制