安卓连接到本地主机
由于wamp服务器,我正在尝试将我的Android应用程序连接到本地主机URL,但它不起作用。我在这里的目标是获取json数据并解析这些数据。对于我的测试,我使用的是设备而不是模拟器,我在AndroidManifest中使用权限.xml:
<uses-permission android:name="android.permission.INTERNET" />
我的网址看起来像这样:
String url = "http://10.0.2.2:8080/tests/PhpProject1/connectionBDD.php";
我试过了:
http://localhost/
http://10.0.2.2:8080/
http://10.0.2.2/
但它从未奏效:
java.net.ConnectException: failed to connect to localhost/127.0.0.1 (port 80): connect failed: ECONNREFUSED (Connection refused)
failed to connect to /10.0.2.2 (port 8080): connect failed: ETIMEDOUT (Connection timed out)
java.net.ConnectException: failed to connect to /10.0.2.2 (port 80): connect failed: ETIMEDOUT (Connection timed out)
然后我尝试使用在互联网上找到的json url测试:http://headers.jsontest.com/
它工作得很好,我在这个地址得到了json数据。所以我想我的代码很好,这里的问题是我的本地主机网址,我不知道它应该是什么确切的形式。我阅读了许多关于它的帖子,但我没有找到解决方案。
这是我的代码:
主要活动 :
public class MainActivity extends Activity {
private String url = "http://10.0.2.2:8080/tests/PhpProject1/connectionBDD.php";
private ListView lv = null;
private Button bGetData;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final JsonDownloaderTask task = new JsonDownloaderTask(this);
lv = (ListView) findViewById(R.id.list);
bGetData = (Button)findViewById(R.id.getdata);
bGetData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
task.execute(url);
}
});
}
public void jsonTaskComplete(JSONArray data){
//todo
}
}
异步任务 :
public class JsonDownloaderTask extends AsyncTask<String, String, JSONArray> {
MainActivity ma;
public JsonDownloaderTask(MainActivity main){
ma = main;
}
@Override
protected JSONArray doInBackground(String... url) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONArray jsonArray = null;
try {
jsonArray = jParser.getJSONFromUrl(url[0]);
} catch (IOException e) {
e.printStackTrace();
}
return jsonArray;
}
protected void onPostExecute(JSONArray data){
ma.jsonTaskComplete(data);
}
}
JSONParser :
public class JSONParser {
String data = "";
JSONArray jsonArray = null;
InputStream is = null;
public JSONParser(){}
// Method to download json data from url
public JSONArray getJSONFromUrl(String strUrl) throws IOException{
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
is = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
is.close();
data = sb.toString();
//br.close();
jsonArray = new JSONArray(data);
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
is.close();
}
return jsonArray;
}
}