У меня проблема. Я хочу подключить свое приложение android к API PHP, который работает на моем локальном хосте. Но в этом коде он всегда выдает «Catch 1», и я даже пытался распечатать исключение, но это не сработало. Вот код моей MainActivity:
package com.example.dbtest;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.Console;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private EditText etUsername;
private EditText etPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUsername = findViewById(R.id.editTextUsername);
etPassword = findViewById(R.id.editTextPassword);
}
public void register(View view) {
Log.d("MainActivity", "Button clicked");
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
String url = "http://app.test/test.php?username="+ username +"&password="+ password;
new MyAsyncTaskgetNews().execute(url);
}
public class MyAsyncTaskgetNews extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
//before works
}
@Override
protected String doInBackground(String... params) {
Log.d("MainActivity","In Background");
// TODO Auto-generated method stub
try {
String NewsData;
//define the url we have to connect with
URL url = new URL(params[0]);
//make connect with url and send request
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//waiting for 7000ms for response
urlConnection.setConnectTimeout(7000);//set timeout to 5 seconds
try {
//getting the response data
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
//convert the stream to string
NewsData = ConvertInputToStringNoChange(in);
//send to display data
publishProgress(NewsData);
} finally {
//end connection
urlConnection.disconnect();
}
}catch (Exception ex)
{
Log.d("MainActivity", "Catch 1");
}
return null;
}
protected void onProgressUpdate(String... progress) {
try {
Log.d("MainActivity","In Progress");
JSONObject json = new JSONObject(progress[0]);
//display response data
Toast.makeText(getApplicationContext(),json.getString("msg"),Toast.LENGTH_LONG).show();
} catch (Exception ex) {
Log.d("MainActivity","Catch 2");
}
}
protected void onPostExecute(String result2){
}
}
// this method convert any stream to string
public static String ConvertInputToStringNoChange(InputStream inputStream) {
BufferedReader bureader=new BufferedReader( new InputStreamReader(inputStream));
String line ;
String linereultcal="";
try{
while((line=bureader.readLine())!=null) {
linereultcal += line;
}
inputStream.close();
}catch (Exception ex){}
return linereultcal;
}
}
Мой PHP API очень прост, так что не go слишком сильно на меня! Но я несколько раз проверял, работает ли API, я могу успешно добавлять данные в свою базу данных! Думаю, проблема в моем коде android. Вот код моего PHP API:
<?php
$host = "localhost";
$user = "root";
$DBpassword = "Fenja2808";
$database = "demo";
$connect = mysqli_connect($host,$user,$DBpassword,$database);
if(mysqli_connect_errno())
{
die("Error in connection: " . mysqli_connect_errno());
return;
}
// get the data from html request
$username = $_GET['username'];
$password = $_GET['password'];
// define the query
$query = "INSERT INTO user(username,password) values('$username','$password');";
$result = mysqli_query($connect, $query);
if(!$result)
{
$output = "{'msg':'Inserting failed'}";
}
else
{
$output = "{'msg':'Insterting succsessfull'}";
}
print($output);
mysqli_close($connect);
?>
Вот мой Stacktrace по запросу!
2020-06-19 11:03:21.467 3017-3663/com.example.dbtest W/System.err: java.net.ConnectException: Connection refused
2020-06-19 11:03:21.518 3017-3663/com.example.dbtest W/System.err: at java.net.PlainSocketImpl.socketConnect(Native Method)
2020-06-19 11:03:21.518 3017-3663/com.example.dbtest W/System.err: at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:334)
2020-06-19 11:03:21.518 3017-3663/com.example.dbtest W/System.err: at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:196)
2020-06-19 11:03:21.518 3017-3663/com.example.dbtest W/System.err: at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
2020-06-19 11:03:21.518 3017-3663/com.example.dbtest W/System.err: at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
2020-06-19 11:03:21.518 3017-3663/com.example.dbtest W/System.err: at java.net.Socket.connect(Socket.java:605)
2020-06-19 11:03:21.518 3017-3663/com.example.dbtest W/System.err: at com.android.okhttp.internal.Platform.connectSocket(Platform.java:113)
2020-06-19 11:03:21.518 3017-3663/com.example.dbtest W/System.err: at com.android.okhttp.Connection.connectSocket(Connection.java:196)
2020-06-19 11:03:21.518 3017-3663/com.example.dbtest W/System.err: at com.android.okhttp.Connection.connect(Connection.java:172)
2020-06-19 11:03:21.518 3017-3663/com.example.dbtest W/System.err: at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:367)
2020-06-19 11:03:21.518 3017-3663/com.example.dbtest W/System.err: at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:130)
2020-06-19 11:03:21.518 3017-3663/com.example.dbtest W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:329)
2020-06-19 11:03:21.519 3017-3663/com.example.dbtest W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:246)
2020-06-19 11:03:21.519 3017-3663/com.example.dbtest W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:457)
2020-06-19 11:03:21.519 3017-3663/com.example.dbtest W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:405)
2020-06-19 11:03:21.519 3017-3663/com.example.dbtest W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:243)
2020-06-19 11:03:21.521 3017-3663/com.example.dbtest W/System.err: at com.example.dbtest.MainActivity$MyAsyncTaskgetNews.doInBackground(MainActivity.java:69)
2020-06-19 11:03:21.521 3017-3663/com.example.dbtest W/System.err: at com.example.dbtest.MainActivity$MyAsyncTaskgetNews.doInBackground(MainActivity.java:44)
2020-06-19 11:03:21.522 3017-3663/com.example.dbtest W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:305)
2020-06-19 11:03:21.522 3017-3663/com.example.dbtest W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
2020-06-19 11:03:21.523 3017-3663/com.example.dbtest W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
2020-06-19 11:03:21.523 3017-3663/com.example.dbtest W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
2020-06-19 11:03:21.523 3017-3663/com.example.dbtest W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
2020-06-19 11:03:21.523 3017-3663/com.example.dbtest W/System.err: at java.lang.Thread.run(Thread.java:761)
Кто-нибудь знает, в чем может быть проблема? Любая помощь приветствуется.
PS: Извините за мой плохой английский sh, это не мой родной язык.