gpt4 book ai didi

java - 为什么我的应用程序在尝试建立 http 连接时不断崩溃?

转载 作者:行者123 更新时间:2023-12-02 04:09:22 25 4
gpt4 key购买 nike

我是 Android 和 LAMP 新手。我在 MySQL 服务器上有一些数据,我正在尝试编写一个应用程序来访问这些数据。
同时,我想做的就是按下一个按钮并获取特定信息(URL 是硬编码的)。当我在 chrome 中输入网址(在我的 Android 手机上运行)时,我得到了我正在寻找的内容,但是当我尝试通过应用程序获取相同的信息时,应用程序崩溃了。这是代码:

    public void getInfo(View view) throws Exception {

try {
URL url = new URL("http://192.168.1.57:80/TOTSphp/getAllUsersInfo.php");

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "TOTS");
//int responseCode = conn.getResponseCode();

BufferedReader in;
conn.setDoOutput(true);
conn.setDoInput(true);
try {
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;

StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
in.close();
}
} finally {
conn.disconnect();
}

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

代码出现在onCreate()之后。方法并通过带有 android:onClick="getInfo" 的按钮调用.

在尝试寻找答案时,我补充道:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />

AndroidManifest.xml ,但这似乎不起作用......

非常感谢!!!

最佳答案

您必须定义AsyncTask才能建立连接..

在按钮点击中调用下面的AsyncTask

new AsyncTaskGetData().execute();

示例

private class AsyncTaskGetData extends AsyncTask<String, String, String> {

ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(signInScreen);
pDialog.setMessage(getString(R.string.please_wait));
pDialog.setCancelable(false);
pDialog.show();
}

@Override
protected String doInBackground(String... arg0) {
try {
URL url = new URL("http://192.168.1.57:80/TOTSphp/getAllUsersInfo.php");

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "TOTS");
//int responseCode = conn.getResponseCode();

BufferedReader in;
conn.setDoOutput(true);
conn.setDoInput(true);
try {
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;

StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
in.close();
}
} finally {
conn.disconnect();
}

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

@Override
protected void onPostExecute(String email) {
// Dismiss the progress dialog
if(pDialog.isShowing()) {
pDialog.dismiss();
}

}
}

关于java - 为什么我的应用程序在尝试建立 http 连接时不断崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33937239/

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