我正在尝试连接到我的本地主机服务器上的一个php工作正常,但我无法读取那里的内容。
下面是我的代码:package com.example.klaussius.probandoconexionservidor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import serverDataRead.ReadUsers;
public class Principal extends AppCompatActivity {
TextView tvText;
Button btGetInfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_principal);
// TextView for our text
tvText = (TextView)findViewById(R.id.tvText);
// Button to get text
btGetInfo = (Button)findViewById(R.id.btGetInfo);
btGetInfo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new leerDatos().execute();
}
});
}
private class leerDatos extends AsyncTask<String,Void,String> {
@Override
protected String doInBackground(String... strings) {
ReadUsers reader = new ReadUsers();
return reader.readUsers();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
tvText.setText(s);
}
}
}
方法readUsers在readUsers:
类中package serverDataRead;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class ReadUsers {
public String texto;
public String readUsers(){
try {
String link = "http://127.0.0.1/api/usersQuery.php";
URL url = new URL(link);
HttpURLConnection con = HttpURLConnection)url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
texto = bufferedReader.readLine();
} catch (Exception e) {
texto = "Fail!";
e.printStackTrace();
} finally {
return texto;
}
}
}
布局:
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btGetInfo"
android:text="@string/getText" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tvText" />
</LinearLayout>
我得到的错误:W/系统。错误:java.net.ConnectException: Connection refused
提前感谢您的帮助。
如果您使用的是模拟器而不是genymotion,则使用10.0.2.2
而不是localhost
,因此url将是" http://10.0.2.2/api/hostsQuery.php
",如果您使用genymotion,则将localhost
替换为10.0.3.2
,因此url将是"http://10.0.3.2/api/hostsQuery.php"
让我知道这是否适合你
解决方案:
HttpURLConnection con = (HttpURLConnection) url.openConnection();