我是学习android开发的初学者。我使用wamp
服务器和php
创建了一个简单的登录应用程序。将android studio连接到服务器和php script
的代码无效。任何人都可以解决它。
package com.example.lenovo.login_demo;
public class MainActivity extends AppCompatActivity {
public int count = 0;
public Button log;
public String a;
public String b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
log = (Button) findViewById(R.id.log);
final Intent in = new Intent(this,second.class);
Button sign = (Button)findViewById(R.id.sign);
log.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText abc = (EditText) findViewById(R.id.user);
EditText cba = (EditText) findViewById(R.id.pass);
a = abc.getText().toString();
b = cba.getText().toString();
log();
}
});
sign.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(in);
}
});
}
public void log(){
Background back = new Background(this);
back.execute(a,b);
}
这是主要的活动。下面是后台类的代码,它建立了连接。
package com.example.lenovo.login_demo;
public class Background extends AsyncTask<String, Void, String> {
Context context ;
String res ;
Toast t;
Background(Context c){
context = c;
}
@Override
protected String doInBackground(String... params) {
String login_url = "http://192.168.225.75/log.php";
try {
String email = params[0];
String pass = params[1];
URL url = new URL(login_url);
HttpURLConnection h = (HttpURLConnection)url.openConnection();
h.setRequestMethod("POST");
h.setDoOutput(true);
h.setDoInput(true);
OutputStream os = h.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
String data = URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(email,"UTF-8")+"&"+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(pass,"UTF-8");
bw.write(data);
bw.flush();
bw.close();
InputStream is = h.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is,"iso-8859-1"));
res = "";
String line ="" ;
while((line = br.readLine())!=null){
res = res + line;
}
br.close();
is.close();
h.disconnect();
} catch (MalformedURLException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
return res;
}
@Override
protected void onPreExecute() {
t = new Toast(context);
}
@Override
protected void onPostExecute(String aVoid) {
t.makeText(context,"its"+ res,Toast.LENGTH_SHORT).show();
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
我没有包含php文件,因为它们正常工作,在测试时没有用android studio连接它们。