I've checked most of the topics about the same problem, but I couldn't find a solution.
My Android
app connects to a WCF
service using the HttpURLConnection
and it works fine when I use the IP address of the machine that hosts the service. However, when I replace it with a host name it can not connect. The connection method that I have is quite standard:
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
The exception is:
java.net.UnknownHostException: Unable to resolve host "myHostname": No address associated with hostname"
myHostname is my actual host name.
It works fine when I use the same url on my PC (both with the IP and with the host name).
On the phone it works only if i am using the IP. Both in the app or in the mobile browser.
I have added the necessary permissions in the AndroidManifest.xml
:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
Could it be something with the permissions to the server that hosts the service? It's an internal server and all machines are connected to an internal Wi-Fi.network. But it works with the IP...
EDIT: I forgot to mention that I am using a physical device instead of the emulator.
It is all right. Android tells you that the phone cannot resolve the name "myHostname". It depends on the topology of your.network. I think that the phone is connected with wifi on an access point that has a wired connection to the lan on which there are you pc and your myHostname host. Your pc got a dns server on its lan connection or just resolve the name with lan broadcasting. Surely you have not configured a dns server on the connection in use on your phone. If you have a dns server on your lan, than set it on the connection, otherwise I don't think that a phone can resolve by broadcast.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.