我正在尝试使用 POST 将数据从 Android 应用程序发送到 PHP,PHP 会将其转发到 MySQL 数据库并给出响应。应用程序崩溃。有人可以帮助我吗。
@Override
public void onClick(View view) {
try {
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("p", "UTF-8") + "=" + URLEncoder.encode(p, "UTF-8") + "&" +
URLEncoder.encode("q", "UTF-8") + "=" + URLEncoder.encode(q, "UTF-8") + "&" +
URLEncoder.encode("r", "UTF-8") + "=" + URLEncoder.encode(r, "UTF-8") + "&" +
URLEncoder.encode("s", "UTF-8") + "=" + URLEncoder.encode(s, "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();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
最佳答案
检查你的帖子!!
你在 UI 线程上运行 http 请求,所以你得到错误。
尝试创建一个新线程
new Thread(new Runnable() {
@Override
public void run() {
try {
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("p","UTF-8")+"="+URLEncoder.encode(p,"UTF-8")+"&"
+URLEncoder.encode("q","UTF-8")+"="+URLEncoder.encode(q,"UTF-8")+"&"
+URLEncoder.encode("r","UTF-8")+"="+URLEncoder.encode(r,"UTF-8")+"&"
+URLEncoder.encode("s","UTF-8")+"="+URLEncoder.encode(s,"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();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
关于php - 从 Android 应用程序向 PHP 发送帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49003530/