使用主机名时,HttpURLConnection无法解析主机

时间:2015-10-16 12:56:44

标签: java android httpurlconnection

我已经检查了大部分有关同一问题的主题,但我找不到解决方案。

我的Android应用使用WCF连接到HttpURLConnection服务,当我使用托管服务的计算机的IP地址时,它可以正常工作。但是,当我用主机名替换它时,它无法连接。我拥有的连接方法非常标准:

public static String getData(RequestPackage requestPackage) {
        BufferedReader reader = null;
        HttpURLConnection con = null;
        String uri = requestPackage.getUri();
        String response = "";

        try {
            URL url = new URL(uri);
            con = (HttpURLConnection) url.openConnection();
            con.setReadTimeout(requestPackage.getReadTimeout());
            con.setConnectTimeout(requestPackage.getConTimeout());
            con.setRequestMethod(requestPackage.getMethod());
            con.setDoInput(requestPackage.isDoInput());
            con.setDoOutput(requestPackage.isDoOutput());

            JSONObject user = new JSONObject(requestPackage.getParams());

            OutputStream os = con.getOutputStream(); // the exception is thrown here
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(user.toString());
            writer.flush();
            writer.close();
            os.close();

            // Get response from the service
            int responseCode = con.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                // more code...
            }else
                // more code

例外是:

  

java.net.UnknownHostException:无法解析主机" myHostname":否   与主机名相关联的地址"

myHostname是我的实际主机名。

当我在我的PC上使用相同的URL(包括IP和主机名)时,它工作正常。

在手机上它只有在我使用IP时才有效。无论是在应用程序中还是在移动浏览器中。

我在AndroidManifest.xml

中添加了必要的权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

是否具有托管服务的服务器的权限? 它是内部服务器,所有计算机都连接到内部Wi-Fi网络。但它适用于IP ......

编辑:我忘了提到我使用的是物理设备而不是模拟器。

0 个答案:

没有答案
相关问题