gpt4 book ai didi

php - 本地主机不工作,但网站在 Android 中工作

转载 作者:行者123 更新时间:2023-11-29 08:14:55 25 4
gpt4 key购买 nike

我正在学习Android。我正在尝试从 Android 读取 PHP 输出(通过 JSON )。

如果我给出站点 URL,它就会获取该值。如果您进入该网站,它会显示如下 Json 代码。

http://cpriyankara.coolpage.biz/employee_details.php ”;

{"emp_info":[{"员工姓名":"Adam","员工编号":"101700"},{"员工姓名":"约翰","员工编号":"101701"},{ "员工姓名":"Paul","员工编号":"101702"},{"员工姓名":"马克","员工编号":"101703"},{"员工姓名":"唐纳德","员工编号":"101704"},{"员工姓名":"Brain","员工编号":"101705"},{"员工姓名":"Kevin","员工编号":"101706"}]}

如果我给我的本地主机 PHP 站点,它也会以 Json 格式显示,如上面所示。 (我正在使用 WAMPSERVER 运行 PHP)

{"emp_info":[{"员工姓名":"Adam","员工编号":"101700"},{"员工姓名":"约翰","员工编号":"101701"},{ "员工姓名":"Paul","员工编号":"101702"},{"员工姓名":"马克","员工编号":"101703"},{"员工姓名":"唐纳德","员工编号":"101704"},{"员工姓名":"Brain","员工编号":"101705"},{"员工姓名":"Kevin","员工编号":"101706"}]}

但是在 Android 中,如果我提供站点,它会显示结果,但如果我提供本地主机地址,它会说应用程序意外停止。

请告诉我为什么??在这种情况下,我如何才能看到错误或异常。

我在下面提供了 PHP 和 Android 代码。

PHP 代码:

<?php
$host=""; //replace with database
$username="root"; //replace with database username
$password="root"; //replace with database password
$db_name="and"; //replace with database name

$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select * from emp_info";
$result = mysql_query($sql);
$json = array();

if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['emp_info'][]=$row;
}
}
mysql_close($con);
echo json_encode($json);
?>

Android Java 代码:

在下面的代码中,我将 URL 更改为本地主机 URL

包com.example.phpmysql;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MainActivity extends Activity {
private String jsonResult;
Private String url = "http://cpriyankara.coolpage.biz/employee_details.php";

private ListView listView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
accessWebService();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}

catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));

try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}

catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}

@Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task

public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}

// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();

try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("emp_info");

for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("employee name");
String number = jsonChildNode.optString("employee no");
String outPut = name + "-" + number;
employeeList.add(createEmployee("employees", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}

SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
android.R.layout.simple_list_item_1,
new String[] { "employees" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
}

private HashMap<String, String> createEmployee(String name, String number) {
HashMap<String, String> employeeNameNo = new HashMap<String, String>();
employeeNameNo.put(name, number);
return employeeNameNo;
}
}

最佳答案

当本地主机工作时,我假设您是从 http://cpriyankara.coolpage.biz/employee_details.php 的计算机发出请求的。托管地址正确吗?

localhost 的意思是“我现在正在发出请求的这台机器”。

因此,除非您的 Android 机器运行了一个可以使用 localhost 访问名为/employee_details.php 的文件的 Web 服务器,否则该服务器将无法工作。

关于php - 本地主机不工作,但网站在 Android 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20826823/

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