我正在尝试使用HttpURLConnection和PHP文件通过MYsql服务器获取数据。问题是连接没有建立和断开。 你能帮我弄清一下缺少的部分吗?
编辑(已解决) - >问题是我在Android主要活动中建立了互联网连接。我必须为背景互联网操作制作不同的Class。谢谢Neel的帮助。
注释: 我做了下面的Toast测试,但它没有显示任何内容。 我在清单文件中添加了Internet权限。 我检查了我的日志,我发现""错误关闭InputStream""出现。
我的Java代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cabinet_viewer);
String reference = "GetCoreSites";
String Myreturndata = operations(reference);
test = (TextView) findViewById(R.id.testtxt);
test.setText(Myreturndata);
public String operations (String data){
String coresiteurl = "http://127.0.0.1/webapp/coresitesquery.php";
String reference = data;
String corestemp = "test";
String line = "";
if (reference.equals("GetCoreSites")) {
try {
URL url = new URL(coresiteurl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
InputStream IS = httpURLConnection.getInputStream();
Log.i(TAG, "gettingstream");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(IS, "iso-8859-1"));
while ((line = bufferedReader.readLine()) != null) {
corestemp+= line;
}
IS.close();
bufferedReader.close();
httpURLConnection.disconnect();
return corestemp;
} catch (MalformedURLException e) {
Log.i(TAG, "Error closing InputStream");
e.printStackTrace();
} catch (IOException e) {
Log.i(TAG, "Error closing InputStream");
e.printStackTrace();
}
}
return corestemp;
}
我的PHP文件:
<?php
require "init.php";
$query = mysqli_query($con,"SELECT core_site FROM core_sites");
$coresites = [];
while($row = mysqli_fetch_assoc($query)){
$coresites[] = $row['core_site'];
}
print_r($coresites);
?>
当我通过broswer访问我的php时,它正在工作并生成输出:
Array ( [0] => Abbasya [1] => Alex Auto [2] => Alex Post [3] => Banisweif [4] => Nasr City [5] => Ramsis TE [6] => Smart Village )
非常感谢您的支持:)