我有带有wamp服务器的Android Studio。我试图使用php文件访问phpmyadmin上的MySql数据库。我尝试过模拟器和Android设备。我总是收到这个错误:
org.apache.http.conn.HttpHostConnectException: Connection to http://10.0.2.2:8080 refused
这是我的MainActivity.jav文件
public class MainActivity extends ActionBarActivity {
private TextView responseTView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.responseTView = (TextView) findViewById(R.id.response);
new getDetails().execute(new SqlConnector());
}
private void setTextToTextView(JSONArray jsonArray) {
String s = "";
for(int i=0; i<jsonArray.length();i++) {
JSONObject obj = null;
try {
obj = jsonArray.getJSONObject(i);
s = s + "ID: " + obj.getString("id") + "Customer Name:" + obj.getString("Customer");
}
catch(JSONException e) {
e.printStackTrace();
}
}
this.responseTView.setText(s);
}
private class getDetails extends AsyncTask<SqlConnector,Long,JSONArray> {
@Override
protected JSONArray doInBackground(SqlConnector... params) {
return params[0].getDetailsinJson();
}
@Override
protected void onPostExecute(JSONArray jsonArray) {
setTextToTextView(jsonArray);
}
}
}
这是我的SqlConnector.java文件
public class SqlConnector {
public JSONArray getDetailsinJson() {
String url = "http://10.0.2.2:8080/D:/Database/main1.php";
HttpEntity httpEntity = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
Log.d("This is inside HTTP try block.","No error..");
HttpResponse httpResponse = httpClient.execute(httpGet); //Using Logs, it's this line that brings on the error. That's my understanding.
httpEntity=httpResponse.getEntity();
}
catch(ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
Log.d("Inside SqlConnector Class", "ajsdhlk");
JSONArray jsonArray = null;
if(httpEntity != null) {
try {
String response= EntityUtils.toString(httpEntity);
Log.e("This is the response", response);
jsonArray = new JSONArray(response);
}
catch(JSONException e) {
Log.d("This is inside Catch block.","Error in JSONArray");
e.printStackTrace();
}
catch(IOException e) {
Log.d("This is inside catch block.","IOException");
e.printStackTrace();
}
}
return jsonArray;
}
}
我已经在Stackoverflow上阅读了很多关于类似问题的帖子。但是,在尝试了很多事情之后,我无法克服这个错误。我尝试更改我使用的IP,但它没有帮助。请帮忙。 我是Android Studio的新手,所以请解释一下解决方案。非常感谢您的帮助。
答案 0 :(得分:0)
经过几个小时的尝试。我改变了我的服务器。我使用在线网站托管网站来存储我的文件。并且,这以某种方式阻止了这个错误。如果您认为还有其他方法,请使用wamp然后请告诉我。
答案 1 :(得分:0)
我设法通过从cmd写我的IP地址来解决这个问题 - &gt; url中的ipconfig:
字符串网址=&#34; http://192.168.x.x/D:/Database/main1.php&#34 ;;