Java Android 连接到本地主机

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21811789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:47:55  来源:igfitidea点击:

Android connection to localhost

javaandroidjsonlocalhostwamp

提问by AlexDG

I'm trying to connect my android application to a local host url thanks to wamp server but it doesn't work. My goal here, is to fetch json data and parse these data. For my test, i'm using a device not the emulator and i use permission in AndroidManifest.xml :

由于 wamp 服务器,我正在尝试将我的 android 应用程序连接到本地主机 url,但它不起作用。我的目标是获取 json 数据并解析这些数据。对于我的测试,我使用的是设备而不是模拟器,并且我在 AndroidManifest.xml 中使用了权限:

<uses-permission android:name="android.permission.INTERNET" />

My url looks like this :

我的网址如下所示:

String url = "http://10.0.2.2:8080/tests/PhpProject1/connectionBDD.php";

i tried :

我试过 :

http://localhost/
http://10.0.2.2:8080/
http://10.0.2.2/

But it never worked so far :

但到目前为止它从未奏效:

    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)

Then i tried with a json url test found on the internet : http://headers.jsontest.com/

然后我尝试在互联网上找到一个 json url 测试:http: //headers.jsontest.com/

It worked really good and i got json data at this address. So i guess my code is good and the issue here is my localhost url, i don't know what should be its exact form.. I read many threads about it but i didn't find a solution.

它工作得非常好,我在这个地址得到了 json 数据。所以我想我的代码很好,这里的问题是我的本地主机 url,我不知道它的确切形式应该是什么..我阅读了很多关于它的线程,但我没有找到解决方案。

Here my code :

这是我的代码:

Main activity :

主要活动 :

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
    }   
}

AsyncTask :

异步任务:

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 :

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;
    }
}

采纳答案by Ajay S

First you have to bind the IP address of the machine where your server is running in the eclipse settings.

首先,您必须在 eclipse 设置中绑定运行服务器的机器的 IP 地址。

You can do this like this.

你可以这样做。

Eclipse Run Configuration

Eclipse 运行配置

Right click on the PHPproject in the eclipse then Run Configuration then In the Web Applicationwhere you will find the Argumenttab. Now here give the port and LAN IP address of your machine on which your server is running.

右键单击PHPEclipse 中的项目,然后单击“运行配置”,然后在Web Application其中找到Argument选项卡。现在在这里提供运行服务器的机器的端口和 LAN IP 地址。

Something like this --port=8888 --address=192.168.1.6then update the URL to http://192.168.1.6:8080/tests/PhpProject1/connectionBDD.php

像这样的--port=8888 --address=192.168.1.6然后将 URL 更新为http://192.168.1.6:8080/tests/PhpProject1/connectionBDD.php

Here in my case this is my LAN IP address 192.168.1.6, there you will have to find it using the network command like ipconfig, ifconfigand use that IP address.

在我的情况下,这是我的 LAN IP 地址 192.168.1.6,您必须使用类似的网络命令找到它ipconfigifconfig并使用该 IP 地址。

回答by Michael Aaron Safyan

If you try to connect to "localhost", it will resolve to the Android device, not to your own localhost (unless you are running within the emulator). What I recommend for development is to add an overflow menu in the action bar that has an entry named "Settings" that provides a Settings activity for specifying application settings, and to have a "Developer options" entry in "Settings" that lets you specify a custom server address to use. During development, you can use this option to enter a custom server address for your app. (You will need a real server address that is actually reachable over the Internet rather than using localhost for this).

如果您尝试连接到“localhost”,它将解析为 Android 设备,而不是您自己的 localhost(除非您在模拟器中运行)。我推荐的开发是在操作栏中添加一个溢出菜单,该菜单具有一个名为“设置”的条目,该条目提供用于指定应用程序设置的设置活动,并在“设置”中有一个“开发人员选项”条目,可让您指定要使用的自定义服务器地址。在开发过程中,您可以使用此选项为您的应用程序输入自定义服务器地址。(您将需要一个可通过 Internet 实际访问的真实服务器地址,而不是为此使用 localhost)。

回答by user3316041

IP-address 10.0.2.2 is used to fetch data from the emulator. Localhost will always point to the emulator/android device running the application. To let your device fetch data from your pc, it should be in the same network (connected by WiFi to your router) and you should use the local IP-address of your pc (normally a 192.168.1.x-number).

IP 地址 10.0.2.2 用于从模拟器获取数据。本地主机将始终指向运行应用程序的模拟器/安卓设备。要让您的设备从您的电脑获取数据,它应该在同一网络中(通过 WiFi 连接到您的路由器),并且您应该使用您电脑的本地 IP 地址(通常是 192.168.1.x 号码)。

回答by Krishna

One simple way i know is keep mobile data on and share wifi . Connect your laptop or computer to this wifi . Now see ip of ur laptop or desktop. Call service from ur phone . Since your phone and your computer are in same network now.

我知道的一种简单方法是保持移动数据和共享 wifi。将您的笔记本电脑或计算机连接到此 wifi。现在查看您的笔记本电脑或台式机的 ip。用您的电话呼叫服务。由于您的手机和您的计算机现在在同一网络中。

回答by Songlin

I assume you are trying to access web service available on your PC from either an android simulator or a real device.

我假设您正在尝试从 Android 模拟器或真实设备访问 PC 上可用的 Web 服务。

For an android emulator, you must NOTjust use "localhost", because "localhost" means android emulator itself, NOTthe host PC.

对于 android 模拟器,您不能只使用“localhost”,因为“localhost”表示 android 模拟器本身,而不是主机 PC。

you need modify the /etc/hosts file or the simulator or real device. add a line like "192.168.0.100 service.local".

您需要修改 /etc/hosts 文件或模拟器或真实设备。添加像“192.168.0.100 service.local”这样的一行。

回答by Saggy

I tried "10.0.2.2:80/mysitename/page.php"Miracle happened, it's working now. I am on Mac and using XAMPP for server.

我试过“10.0.2.2:80/mysitename/page.php”奇迹发生了,它现在可以工作了。我在 Mac 上使用 XAMPP 作为服务器。

You can change port no. to 80 and try. port 8080 was not working for me!

您可以更改端口号。到 80 并尝试。端口 8080 对我不起作用!

Cheers.

干杯。

回答by Kavita_p

if you are using your phone instead of emulator and running services on localhost then in url instead of '10.0.2.2' use IP address of your PC.

如果您使用手机而不是模拟器并在本地主机上运行服务,则在 url 而不是“10.0.2.2”中使用您 PC 的 IP 地址。

回答by Kavita_p

Just Install the "conveyor by Keyoti" the extension in Visual studio and it will generate a url according to your ip address automatically. here's the link:

只需在 Visual Studio 中安装“ Transfer by Keyoti”扩展程序,它就会根据您的 IP 地址自动生成一个 url。这是链接:

conveyor

输送带

so far so good....!

到目前为止,一切都很好....!

回答by itassets

I solved it by: 1. Adding another android permission in the manifest: "android.permission.ACCESS_NETWORK_STATE" 2. As I'm using xampp, I've shared the xampp folder of the desktop in the network. 3. The xampp is running in a desktop whose ip is 192.168.x.x so the webservice's url instead of beign "http://localhost/myapi..." is "http://192.168.x.x/myapi..."

我通过以下方式解决了这个问题: 1. 在清单中添加另一个 android 权限:“android.permission.ACCESS_NETWORK_STATE” 2. 因为我使用的是 xampp,所以我在网络中共享了桌面的 xampp 文件夹。3. xampp 运行在一个 ip 为 192.168.xx 的桌面上,所以 webservice 的 url 而不是 beign " http://localhost/myapi..." 是 " http://192.168.xx/myapi..."

I tested the app using the emulator and also in a device. Both cases works out.

我使用模拟器和设备测试了该应用程序。两种情况都成立。