我正在尝试connetc到一个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;
}
致命异常:AsyncTask#1 过程:com.example.modernkill_laptop.mysqlproject,PID:18789 java.lang.RuntimeException:执行doInBackground()
时发生错误
答案 0 :(得分:0)
嘿伙计们,所以我找到了解决问题的方法,这就是我试图连接一切的方式。因此,对于尝试连接到PHPMySQL数据库的任何人来说,请按照这个快速简单的教程找到她。解决了我所有的问题。
http://androidcss.com/android/android-php-mysql-login-tutorial/