将Android手机连接到本地主机

时间:2016-04-01 07:54:07

标签: android android-networking androidhttpclient

在我的应用程序中,我使用的是本地服务器上托管的API,可以在网络上访问。在模拟器上它工作正常,因为它连接到适当的网络。当我在手机上使用应用程序时,它不会。

是否可以通过正常的互联网连接通过手机访问本地API?

我使用下面的http代码来访问API。

 public String getResponse(String url, int method, String postParameter) {
    HttpResponse response = null;
    // Creating HTTP client
    HttpClient httpClient = new DefaultHttpClient();
    // Creating HTTP Post
    HttpPost httpPost = new HttpPost(url);

    // Building post parameters
    // key and value pair
    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
    nameValuePair.add(new BasicNameValuePair("jObj", postParameter));

    // Url Encoding the POST parameters
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
    } catch (UnsupportedEncodingException e) {
        // writing error to Log
        e.printStackTrace();
    }

    // Making HTTP Request
    try {
         response = httpClient.execute(httpPost);

        // writing response to log
        Log.d("Http Response:", response.toString());
    } catch (ClientProtocolException e) {
        // writing exception to log
        e.printStackTrace();
    } catch (IOException e) {
        // writing exception to log
        e.printStackTrace();

    } catch (Exception e2) {
        e2.printStackTrace();
    }
    return response.toString();
}

我们可以通过普通互联网进行设置吗?

先谢谢

3 个答案:

答案 0 :(得分:1)

如果您将其托管在本地计算机上,则必须找到在同一网络上连接手机和本地计算机的方法(最常见的是Wifi)。一个简单的解决方法是在Android设备中创建一个热点并将本地计算机连接到它。确保在Android应用程序中设置正确的IP地址。

答案 1 :(得分:0)

找到托管api的本地计算机IP地址 使用ipconfig并传递url中的ip地址 您的网址应该是192.168.0.102,由调制解调器分配。

答案 2 :(得分:0)

我无法发表评论,请检查您的手机是否已连接到您的网络,而不是使用移动数据或网络外的其他WIFI网络。