gpt4 book ai didi

android - 使用 android-Asynctask 连接但仍然出现错误

转载 作者:行者123 更新时间:2023-11-29 02:41:21 25 4
gpt4 key购买 nike

我正在尝试连接到一个 URL,以便我可以使用我的 PHP 文件进行 POST。当我执行这行代码时,我的 Android 应用程序不断崩溃并且不断出现错误:

OutputStream outputStream = httpURLConnection.getOutputStream();

这是我的代码,下面是我在 android studio 中遇到的错误。谢谢。

public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx) {
context = ctx;
}
@Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://www.cs.csub.edu/~zobeid/Android/login.php";
if(type.equals("login")) {
try {
String user_name = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!= null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}

FATAL EXCEPTION: AsyncTask #1 Process: com.example.modernkill_laptop.mysqlproject, PID: 18789 java.lang.RuntimeException: An error occurred while executing doInBackground()

最佳答案

大家好,我找到了解决我的问题的方法,这正是我尝试连接所有内容的方法。因此,对于尝试连接到 PHPMySQL 数据库的任何人,请按照她提供的这个快速简单的教程进行操作。解决了我所有的问题。

http://androidcss.com/android/android-php-mysql-login-tutorial/

关于android - 使用 android-Asynctask 连接但仍然出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43838063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com